How to build a cross-platform desktop app by using Electron.Net?

How to Build a Cross Platform Desktop Apps by Using Electron.Net

This article has information on developing and deploying an application using Electron.Net.

What is Electron?

Electron is an open-source software development framework developed and maintained by GitHub. It allows you to create cross-platform desktop applications using web technologies like Chromium rendering engine and Node.js runtime. It supports Windows, macOS, and Linux operating systems. Many of the popular applications are developed in Electron, such as Microsoft Teams, Visual Studio Code, Skype, Discord, Twitch, and more.

Electron uses all the usual web standards such as HTML, JavaScript, and CSS. If you are a .Net developer and used to work with c#, that’s where Electron.NET comes into the picture.

What is Electron.NET?

Electron.Net is a wrapper around a “normal” Electron application with an embedded ASP. NET Core application. It is an open-source project that allows .NET developers to invoke native Electron APIs using C#. Electron.NET has two components:

  1. Electron.Net API: A NuGet package that adds Electron APIs to an ASP. NET Core project.
  2. Electron.Net CLI: A .NET Core command-line extension that builds and launches Windows, macOS, and Linux platforms applications.

Electron.NET requires below software to be pre-installed:

  1. Node.js
  2. .Net Core 3.1

Once both the above software are installed on your system, you are ready to build your first Electron app using ASP.NET Core 3.1. So let’s start with creating an ASP.NET Core Web application. 

Create ASP.NET Core web application:

You can create an ASP.Net Core web application using the Visual Studio 2019 or VS Code. For this article, lets Visual Studio 2019. With the help of creating a new project option, you can create “Asp.Net Core web application” by choosing the bellow template:

Once you create a web application, Press F5 to build and run the application will open a browser with default ASP. NET Core welcome page. Now you can close the page and return the Visual Studio and stop the debugging. 

Setup Electron.NET:  

Now add the Electron.NET API in your project by installing the Electron.NET API NuGet package with the help of the command below:

PM> Install-Package ElectronNET.API

This package allows us to communicate with “native” Electron API. Once the package is installed, we need to modify the Program.cs and add a using statement for the newly added package.

Using ElectronNET.API; Find the “CreateHostBuilder” static method in the Program.cs and make the below changes:

      public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                    .UseElectron(args);
                });

We are done with the changes in Program.cs, now we need to do a few changes in Startup.cs. Fist add the below using statements:

using ElectronNET.API;

using ElectronNET.API.Entities;

Now find the “Configure” method and add the below lines to the end of body:

      public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                    .UseElectron(args);
                });

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, AsynchronousClient client)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();
            app.UseRequestLocalization();
            app.UseWebSockets();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=BaseCamp}/{action=Index}/{id?}");
            });


if(HybridSupport.IsElectronActive)
            {
                CreateWindow();
            }


        }

Now we need to add “CreateWindow()” in our Starup.cs class to create mail Electron window:

public async void CreateWindow()
        {
  var browserWindowOptions = new BrowserWindowOptions
                {
                    Title = "Demo",
                    Width = 1280,
                    Height = 720,
                    Frame = false,
                    Transparent = true,
                    MinHeight=720,
                    MinWidth=1280,
                    BackgroundColor = "#001b2022",To make the window transparent
                    Icon = @"xyz.ico",
                    Resizable = true,
                    Fullscreenable = true,
                    Maximizable = true,
                    WebPreferences = new WebPreferences
                    {
                        DevTools = false
                    },
                };
            var mainWindow = await Electron.WindowManager.CreateWindowAsync(options);
            await mainWindow.WebContents.Session.ClearCacheAsync();
            mainWindow.OnReadyToShow += () =>
            {
                mainWindow.Show();
                mainWindow.Focus();
            };
        }

As you can see in the above code snippet, we have set different properties of BrowserWindowOptions Class and passed it as an argument to the CreatewindowAsync method. We have also handled the “OnClose” event to terminate the application when the user closes the main window. 

Install the Electron.NET Command line tool:

Electron.NET provides us with a command-line tool to build and deploy the application. To use this command-line tool first, we need to install it, and it is a one-time process. To install the command-line tool, open the command prompt as admin and type the below command in it, and hit enter:

dotnet tool install ElectronNET.CLI –g

I will install the .NET Core global tool that implements a command named “electronize.” You can see the complete list of commands installed on your system by type the following:

dotnet tool list –g

That’s it; we are ready with our first electron application. Now we need to run this application.

Run the Application:

After installing the command-line tool, we need to type the below command in CMD after moving to the application’s root directory:

electronize init 

This is a one-time step, and it will create a manifest file named “electron.manifest.json” and add it to your project.

Now you need to run the below command:

electronize start

The above command will launch the electron application. 

You can also configure the visual studio to do the above step as shown below:

Now you can directly run the electron application using the Visual studio by choosing the above profile and hit the F5 button.

It will open up the above window but not in the browser. 

Build application for different platforms:

To build the installation setup for windows, run the below command:

electronize build /target win

To build the setup for other platforms, run the below commands:

electronize build /target osx

electronize build /target linux

The default targets will produce x64 builds. In certain scenarios, you may want to build a pure x86 application. To support those things, you can define the desired .NET Core runtime, the electron platform, and electron architecture like this:

electronize build /target custom win7-x86;win32 /electron-arch ia32 

The above commands will produce the electron application under the bin/desktop folder.

In case of any queries, do not hesitate to get in touch with an expert.