Using Menu and Tray with Electron
Introduction
Electron is a popular framework for developing desktop applications using web technologies. In this article, you will learn how to integrate menus and tray (system tray) into your applications with Electron. These features, which enhance the user experience, can significantly improve the usability of your application.
Creating a Menu with Electron
To create a menu in Electron, you must first use the 'Menu' module. The code example below shows how you can create a simple menu structure:
const { app, BrowserWindow, Menu } = require('electron');
let mainWindow;
app.whenReady().then(() => {
mainWindow = new BrowserWindow({ width: 800, height: 600 });
const menuTemplate = [
{
label: 'File',
submenu: [
{
label: 'Open',
click: () => { console.log('Open button clicked'); }
},
{
label: 'Exit',
click: () => { app.quit(); }
}
]
}
];
const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
});
Customized Menu Items
You can customize your menu items according to your needs. For example, you can assign different icons and events to make the menu more dynamic. You can add more features to the 'Open' and 'Exit' options in the example above.
Creating a System Tray
The system tray allows users to quickly launch your application while not taking up any interface space. The following example allows you to create a simple tray icon in Electron:
const { Tray, Menu } = require('electron');
let tray;
app.whenReady().then(() => {
tray = new Tray('path/to/icon.png'); // Icon path for the tray icon
const contextMenu = Menu.buildFromTemplate([
{ label: 'Show', click: () => { mainWindow.show(); } },
{ label: 'Exit', click: () => { app.quit(); } }
]);
tray.setToolTip('The application is open.');
tray.setContextMenu(contextMenu);
});
Interaction with Tray
It is quite easy to define the menu that opens when users right-click on the tray icon. In the example above, we configured it so that when users click the 'Show' option, the main window will be shown.
Conclusion
In this article, you learned how to implement a simple menu and system tray integration with Electron. You can use these features especially to enrich user interfaces and to enhance user experience. Now, by using this information, you can start your own menu and tray integrations to improve your application.


Yorum Gönder