Keyboard Shortcuts: Shortcut in Electron.js

- Andrés Cruz

En español

Keyboard Shortcuts: Shortcut in Electron.js

The globalShortcut module can register (or override) a global keyboard shortcut with the operating system so that you can customize the operations for various shortcuts to perform specific functions in each case; For example, the famous Control/Command + S combination to save application state is easy to capture in Electron.js:

const { globalShortcut } = require('electron')
globalShortcut.register('CommandOrControl+S', () => {
 // TO DO
});

To unregister a combination:

globalShortcut.unregister('CommandOrControl+X')

To unregister all shortcuts:

globalShortcut.unregisterAll()

From the menu in Electron.js, we can specify a property called accelerator with which we can also specify the keyboard shortcuts; for example:

menu.js

const { app, ipcMain, Menu, shell, BrowserWindow, globalShortcut } = require('electron')
const { open_file, save_file } = require("./editor-options")

const template = [
   ***
    {
        label: 'File',
        submenu: [
            {
                label: "Save",
                accelerator: 'CommandOrControl+Shift+S',
                click() {
                    const win = BrowserWindow.getFocusedWindow()
                    win.webContents.send('editorchannel', 'file-save')
                }
            },
     },
   ***
]

Remember that the previous material is part of mi curso completo sobre Electron.js

I agree to receive announcements of interest about this Blog.

The globalShortcut module can register (or override) a global hotkey with the operating system, let's see how to use it.

- Andrés Cruz

En español