Search code examples
javascriptelectronshortcut

How to register CommandOrControl alone to globalShortcut in electron.js?


I am working on a tool for dynamically demonstrate what key is press on keyboard. By using globalShortcut module on electorn.js, I am stuck on how to register Control or Alt key alone:

const globalShortcut = require('electron').globalShortcut;

/* Register "ESC" is work */
globalShortcut.register("Escape", () => {
    console.log("Esc")
    win.webContents.send('onInput', "Escape");

  })

/* Register modifiers like "Alt" or "Control" would throw error*/

globalShortcut.register("Alt", () => {
    console.log("Alt")
    win.webContents.send('onInput', "Alt");

  })

I am sure every key is resisted successfully except Available modifiers which was classified by official tutorial. Does anyone know how to fix the problem? Thanks a lot!


Solution

  • Replacing the alt and or ctrl keys with global shortcuts does not seem like a good idea to me. Because it is global shortcuts it could possibly interfere with other functionality (like ctrl+alt+del). There is a package to help with electron-local shortcuts or you can use the menu to use the shortcuts when the window is focussed as described in the electron official docs-local shortcuts.

    Additionally, if you are trying to capture these events while the client is in the browser window, it might be preferred to add event listeners to the key up and key down events as so:

    window.addEventListener('keydown', doSomething, true)
    

    Here are some more examples using the above mentioned method.