不要尝试在渲染线程中监听按键,而是使用主线程。
请参阅 Electron 的 globalShortcut 了解更多信息。
有关可用快捷键组合的列表,请参阅Accelerator。
即使窗口被最小化,此功能也可以工作。
main.js
(主线程)
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')
})
【讨论】: