Integrating with the system tray

In most cases, the users of your application may only use it when required and then minimize or close the app.

You can significantly improve user experience by keeping the application up and running in the background and displaying it in the system tray area. Another essential feature is to have a global keyboard shortcut so that the users of your application can quickly invoke it without needing to use the mouse.

Let's start by integrating the system tray:

  1. First, you need to import the Menu and Tray objects from the Electron framework, the Tray integration, and also the path from Node.js to resolve the path to the Tray icon image:
      const { Menu, Tray } = require('electron');
const path = require('path');

let tray;
  1. Next, create a folder called assets and put a small 16 x 16 image in png format inside it. For the sake of simplicity, let's call it icon.png.
  2. The following code shows how we can create a basic Tray entry with a custom image:
      function createTray() {
const iconPath = path.join(__dirname, 'assets/icon.png');
tray = new Tray(iconPath);

const contextMenu = Menu.buildFromTemplate([
{
label: 'Quit',
type: 'normal',
click() {
app.quit();
}
}
]);

tray.setToolTip('Screenshot Snipping Tool');
tray.setContextMenu(contextMenu);
}
  1. Here, we have created a function called createTray that builds and sets up the Tray component. Now, you need to call this function from within the ready handler:
      app.on('ready', () => {
createTray();
createWindow();
});
  1. Run or restart your Electron application and check out the system tray area. We are using macOS is this example. Notice the custom tooltip content if you hover the mouse cursor over the icon:

  1. If you click on the icon, you should get the Quit menu entry, which is the one we have just defined in the createMenu function:

Now, we can make some minor enhancements to the application's user experience. Let's hide the application window on startup.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.224.103