Back to all posts
Electron in Practice: Registering Shortcuts
Electron
Preface
This article introduces how to register keyboard shortcuts in an Electron app.
Main Process
Registering shortcuts in the main process is straightforward — just make sure to do it after app ready.
Common key mappings: https://www.electronjs.org/docs/latest/api/accelerator
// Register
globalShortcut.register(shortcutKey, shortcutCallback);
// Unregister
globalShortcut.unregister(shortcutKey);
Also, remember to clean up all registered shortcuts when the app quits.
app.on("will-quit", () => {
globalShortcut.unregisterAll();
});
Renderer Process
Registering shortcuts in the renderer process is a bit more involved.
An npm package has been created for this — feel free to use it: https://code.insistime.com/#/qiao-x-shortcut
Initialize IPC Listener in the Main Process
import { shortcutIPCInit } from "qiao-x-shortcut";
shortcutIPCInit({
shortcutCallbackName: () => console.log("shortcutCallbackName from main process"),
});
Preload Setup
shortcut-preload.js
// electron
import { ipcRenderer } from "electron";
/**
* shortcutGlobalIPC
* @returns res
*/
export const shortcutGlobalIPC = async (shortcutKey, shortcutCallbackName) => {
return await ipcRenderer.invoke("ipc-shortcut-global", shortcutKey, shortcutCallbackName);
};
preload.js
// electron
import { contextBridge } from "electron";
// custom preload
import { shortcutGlobalIPC } from "./shortcut-preload.js";
// preload
contextBridge.exposeInMainWorld("electron", {
shortcutGlobalIPC,
});
Calling from the Renderer Process
await window.electron.shortcutGlobalIPC("Command+Control+X", "shortcutCallbackName");
Result
After registering the shortcut Command+Control+X in the renderer process,
the effect is as follows — each time the shortcut is pressed, the main process logs a message:
shortcutCallbackName from main process
shortcutCallbackName from main process
shortcutCallbackName from main process More Articles
- Electron in Practice: Registering an Apple Developer Account
- Electron in Practice: Clipboard
- Electron in Practice: Crash Reporting and Parsing
- Electron in Practice: DMG Installer Customization
- Electron in Practice: Package Size Optimization
- Electron in Practice: Creating icns Icons
- Electron in Practice: Local Logging
- Electron in Practice: Customizing Mac Menus
- Electron in Practice: Mac App Signing and Notarization
- Electron in Practice: Mac Packaging
- Electron in Practice: Managing Electron Projects with Monorepo
- Electron in Practice: Update Strategies
- Electron in Practice: Creating a Window
- Learn Electron in One Article
- Electron - Development Practice: Local Database SQLite