'Simulating out of window keypresses in Electron
I am looking for references how to achieve keypresses out of Electron's window (so even when window is minimized). Similar to AutoHotKey. I was using python to achieve this ( using pynput ) but I wanted to switch to Electron for its ease of creating UI. So far I've tried something like this:
window.addEventListener('keydown', (e) => {
console.log(e)
})
window.dispatchEvent(new KeyboardEvent('keydown', {
key: "e",
keyCode: 69,
code: "KeyE",
which: 69,
shiftKey: false,
ctrlKey: false,
metaKey: true
}));
Even though I am listening for keys properly, this doesn't seem to work as I'd like it to. I would be grateful for recommendations to any further readings, tutorials, etc.
Solution 1:[1]
Instead to trying to listen for key presses in the render thread, use the main thread instead.
See Electron's globalShortcut for more information.
For a list of available shortcut combinations see Accelerator.
This functionality will work even if the window is minimised.
main.js (main thread)
const electronApp = require('electron').app
const electronGlobalShortcut = require('electron').globalShortcut
let window = null;
electronApp.on('ready', () => {
// Create a window.
window = new electronBrowserWindow ({ ... });
// Load the window.
window.loadFile('./index.html')
// Register your global shortcut(s).
electronGlobalShortcut.register('Alt+J', shortcutPressed(); )
// Prove it works.
function shortcutPressed() {
console.log('Alt+J was pressed.');
}
})
app.on('will-quit', () => {
// Don't forget to unregister your global shortcut(s).
globalShortcut.unregister('Alt+J')
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | midnight-coding |
