我想出的唯一方法是在没有onkeydown
监听器具有全局快捷方式和 Electron api 中的 ipc 事件。
首先是免责声明...
使用全局快捷键禁用任何键确实会在您的计算机上全局禁用它!使用全局快捷键时请小心!如果你忘记注销你的快捷方式,或者没有正确处理它,你会发现没有退格键很难修复你的错误!
这就是说这对我有用......
const { app, ipcMain,
globalShortcut,
BrowserWindow,
} = require('electron');
app.on('ready', () => {
// Create the browser window
let mainWindow = new BrowserWindow({width: 800, height: 600});
// and load the index.html of the app
mainWindow.loadUrl('file://' + __dirname + '/index.html');
// Register a 'Backspace' shortcut listener when focused on window
mainWindow.on('focus', () => {
if (mainWindow.isFocused()) {
globalShortcut.register('Backspace', () => {
// Provide feedback or logging here
// If you leave this section blank, you will get no
// response when you try the shortcut (i.e. Backspace).
console.log('Backspace was pressed!'); //comment-out or delete when ready.
});
});
});
// ** THE IMPORTANT PART **
// Unregister a 'Backspace' shortcut listener when leaving window.
mainWindow.on('blur', () => {
globalShortcut.unregister('Backspace');
console.log('Backspace is unregistered!'); //comment-out or delete when ready.
});
});
或者,您可以在 ipc“Toggle”事件处理程序中添加快捷方式,如下所示...
// In the main process
ipcMain.on('disableKey-toggle', (event, keyToDisable) => {
if (!globalShortcut.isRegistered(keyToDisable){
globalShortcut.register(keyToDisable, () => {
console.log(keyToDisable+' is registered!'); //comment-out or delete when ready.
});
} else {
globalShortcut.unregister(keyToDisable);
console.log(keyToDisable+' is unregistered!'); //comment-out or delete when ready.
}
});
// In the render process send the accelerator of the keyToDisable.
// Here we use the 'Backspace' accelerator.
const { ipcRenderer } = require('electron');
ipcRenderer.send('disableKey-toggle', 'Backspace');