Electron.NET: Custom Application Menus

This post will take the existing sample Electron.NET application used in Create a Desktop Application using ASP.NET Core and Electron.NET and Electron.NET with a Web API and expand it to customize the application menu. I leaned heavily on the Electron.NET API Demos repo to guide how this should be done. The code before any changes can be found here.

Menu Controller

While not a requirement I follow the API Demo example of putting the application level menus in its own controller. Add a  MenusController to the  Controllers directory. The following is the full class.

What the above comes down to is building an array of  MenuItem types and then using   Electron.Menu.SetApplicationMenu(menu) to pass the array to Electron which handles replacing the default set of menus with the ones defined in the array.

For most of the items that were on the default set of menus all that is needed to add back the default functionality is to set the  Role to the function you want. For example in the above for a Copy menu item, we can assign  Role to  MenuRole.copy and Electron will handle the implementation of a copy without us having to write any additional code.

Navigate to a page from the application menu

One thing I wanted to be able to do was from a menu create a new contact. It was easy enough to add a top-level menu for Contacts and a sub-item for Create. It took me awhile, but I finally figured out how to build a URL that would work. The following code is the menu items for the Contacts menu.

The ASP.NET Core backend is running on localhost, the key that took me awhile to locate was the port. In the end, I found that the port being used can be found using  BridgeSettings.WebPort.

Include the menu

The final change that is needed is to make sure the new set of menus get rendered. For the sample application open the  _Layout.cshtml file in the  Views/Shared directory. Inside the  head tag add the following line which will force a call to the  MenusController when the application loads.

Wrapping Up

Customizing the application menu ended up being pretty easy. If I hadn’t wanted to navigate to a specific page I would have been done in no time, but hitting the issue with navigation helped me learn more about how Electron.NET is working. You can check out the finished code here.


Also published on Medium.

Leave a Reply

Your email address will not be published. Required fields are marked *