electron程序,如何注册localshortcut本地快捷键?
发布于 作者:苏南大叔 来源:程序如此灵动~
electron
可以注册全局快捷键,但是这个全局快捷键有个问题就是:即使electron
窗体最小化后,这个快捷键仍然可以被响应。那么,新的需求就这么来了,如何注册一个本地快捷键,当窗口没有被激活的时候,对应快捷键并不生效。
本文测试环境:mac
/electron@5.0.2
/electron-loaclshortcut@2.0.2
。文章中涉及到的基础龙套项目是:electron-quick-start
。
安装electron-loaclshortcut
electron
的本地快捷键功能,官方暂时无相关类库,所以是使用第三方类库来实现的。类库的名字是:electron-loaclshortcut
,截至到发稿其最新版是2.0.2
,github
地址如下:
可以通过在项目根目录下面,通过npm
安装electron-loaclshortcut
:
npm install electron-localshortcut --save
这里为什么是--save
,而不是--save-dev
,苏南大叔就不做赘述了。
register
注册本地快捷键
在app
的ready
事件里面,在建立了对应的窗体后,就可以注册loaclshortcut
了。
// mainWindow = new BrowserWindow({});
const electronLocalshortcut = require('electron-localshortcut');
electronLocalshortcut.register(mainWindow, '<shortcut>', () => {
//...
});
在上述demo
中,需要的注意的地方,有两个:
- 需要在
new BrowserWindow
之后,才能注册localshortcut
,这个是和global-shortcut
不一样的地方。 - 上述代码快捷键注册的是
<shortcut>
,您千万别原封照抄,请注意替换相关文字。
更具体的范例
比如,下面的代码是个更具体的例子:
function createWindow () {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
mainWindow.loadFile('index.html')
// 重点代码开始
const electronLocalshortcut = require('electron-localshortcut');
electronLocalshortcut.register(mainWindow, 'CmdOrCtrl+5', () => {
dialog.showMessageBox({
title: "帮助",//信息提示框标题
message: "localshortcut",//信息提示框内容
buttons: ["ok"],//下方显示的按钮
noLink:true, //win下的样式
type: "info",//图标类型
}, function (index) {
console.log(index);
});
});
// 重点代码结束
mainWindow.on('closed', function () {
mainWindow = null
})
}
这个例子中,注册的本地快捷键是:CmdOrCtrl+5
。效果是:当electron
窗体被激活的时候,使用该快捷键可以激活一个dialog
对话框。
其它相关函数
相关函数用到的概率不高,不过,苏南大叔在这里也还是要罗列一下。
isRegistered
是否注册成功
console.log(
electronLocalshortcut.isRegistered(win, 'Ctrl+A')
);
unregister
取消快捷键注册
electronLocalshortcut.unregister(win, 'Ctrl+A');
unregisterAll
取消窗体上所有的快捷键
electronLocalshortcut.unregisterAll(win);
disableAll
禁用窗体上所有快捷键
electronLocalshortcut.disableAll(win);
enableAll
启用窗体上所有快捷键
electronLocalshortcut.enableAll(win);
相关链接
- https://newsn.net/say/electron-globalshortcut.html
- https://newsn.net/say/electron-dialog-messagebox.html
总结
使用了localshorcut
,就可以避免globalshortcut
全局快捷键冲突的尴尬了。更多electron
相关经验文字,请点击苏南大叔的博客:


