Registering global keyboard shortcuts

Now that the minimal system tray menu is up and running, let's provide keyboard support. You can use any key combination of your choice; for example, try Cmd + Alt + Shift + S for macOS or Ctrl + Alt + Shift + S for Linux and Windows. Let's get started:

  1. First, import globalShortcut from the Electron framework, as shown in the following code:
      const { app, BrowserWindow, Menu, Tray, 
globalShortcut } = require('electron');
  1. As you already know, you can provide and render keyboard combinations by utilizing the accelerator property of the menu item:
      function createTray() {
const iconPath = path.join(__dirname, 'assets/icon.png');
tray = new Tray(iconPath);

const contextMenu = Menu.buildFromTemplate([
{
label: 'Show',
type: 'normal',
accelerator: 'CommandOrControl+Alt+Shift+S',
click() {
win.show();
}
},
{
label: 'Quit',
type: 'normal',
click() {
app.quit();
}
}
]);

tray.setToolTip('Screenshot Snipping Tool');
tray.setContextMenu(contextMenu);
}
  1. However, the preceding code doesn't invoke the window when the application is minimized; it mainly serves as a hint that tells your users what combination they should use. We still need to register a global handler, as shown in the following code:
      globalShortcut.register('CommandOrControl+Alt+Shift+S', () => {
if (win) {
win.show();
}
});

  1. As you can see, this was very easy to implement. Once the global shortcut handler has been invoked, we can call win.show() to display the main application window so that that end user can take a desktop screenshot:

  1. Finally, disable the window after taking a screenshot, as shown in the following code:
      fs.writeFile(outputPath, image, err => {
// win.show();

if (err) return console.error(err);
shell.openExternal(`file://${outputPath}`);
});

Congratulations on reaching the end of this chapter! Feel free to extend and improve your desktop snipping tool as you see fit.

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

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