在看到这个问题后,我对您的主题进行了小型研究。首先想到的是 electron 是否可以提供访问按键事件的权限,但根据此
thread,electron 开发人员正在停止 electron 成为一个键盘记录器。因此,我有以下方法解决此问题。我不知道这是否是针对这种情况的最佳方法,但这是我认为可以完成的方式。基本上是围绕 electron-store 构建的,它可用于持久化用户定义的密钥组合。因此,应用程序可以从存储中检索定义的密钥组合(如果没有配置组合,则使用模式提供的默认密钥组合),并使用它注册一个全局快捷键。我提供了如何实现它的步骤。
- 使用 electron-store 安装和配置默认密钥值。如下所示
main.js
const Store = require('electron-store');
const schema = {
defaultKeyCombination: {
type: 'string',
default: 'CommandOrControl+Y'
}
}
const store = new Store({schema});
- 导入此
defaultKeyCombination
,您可以在应用准备就绪时注册全局快捷键。(不要忘记在应用程序销毁时删除全局快捷键)
app.on('ready', () => {
globalShortcut.register(store.get('defaultKeyCombination'), () => {
})
})
从菜单点击(菜单栏>选项>配置)创建并打开另一个browserWindow,让用户使用可用的修饰符和按键代码在输入框中创建/输入加速键组合;最好在输入框下方的新窗口中显示这些内容;
例如:用户可以在浏览器上输入修饰符+按键代码,如CmdOrCtrl
+
A
。
一旦用户按下提交
按钮,使用IPCRenderer将输入的键组合发送到主进程,并将存储器defaultKeyCombination
的值设置为接收到的值。
触发IPC以发送回复告诉用户“请重新启动应用程序”,并在警报或其他地方显示它。
渲染进程
let args = "CmdOrCtrl+A"
ipcRenderer.send('set::keycombine',args)
ipcRenderer.on('done::keycombine', (event, arg) => {
})
主进程
ipcMain.on('set::keycombine', (event, arg) => {
console.log(arg)
store.set('defaultKeyCombination', arg)
event.reply('done::keycombine')
})
一旦应用程序重新启动,存储将加载新配置的键组合并使用它注册快捷事件。
这是我在进行这个小研究时想到的。在这里,我发现了一个名为
iohook的按键事件监听器,但这仅适用于electron 2.XX。在上述过程中可能会出现错误和流程问题,我只是贴了一些代码来获得一个想法。
编辑1:
这是我的样本。在我的index.html中,我定义了一个按钮来调用set()函数。您可以集成inputbox,以便输入命令。一旦使用存储设置了密钥,它就始终使用此新键值进行加载,除非用户更改它。您可以从
electron-store这里了解更多信息。希望这能给您一个想法:)
Main.js
const {app, BrowserWindow, ipcMain } = require('electron')
const Store = require('electron-store');
const schema = {
defaultKeyCombination: {
type: 'string',
default: 'CommandOrControl+Y'
}
}
const store = new Store({schema});
console.log(store.get("defaultKeyCombination"))
function createWindow () {
const window = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
window.loadFile('./index.html')
window.webContents.openDevTools()
}
ipcMain.on('set::keycombine', (event, arg) => {
console.log(arg)
store.set('defaultKeyCombination', arg)
event.reply('done::keycombine', store.get('defaultKeyCombination'))
})
app.wheReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
Renderer.js
const { ipcRenderer } = require('electron')
function set() {
console.log("clicked")
let args = "CmdOrCtrl+A"
ipcRenderer.send('set::keycombine',args)
}
ipcRenderer.on('done::keycombine', (event, arg) => {
console.log("DONEEEEEEEEEE", arg)
})
event.reply
方法似乎不存在。出现了异常。 - wullxz