本节咱们学习 Electron
中的键盘快捷键。在 Electron
中,键盘快捷键被称作加速器,它们可能分派到使用程序菜单中的操纵上,也可能全局分派,所以纵然你的使用程序没有获得键盘外围,它们也可能被触发。
Electron
中有主过程和渲染过程这两种进行,所以咱们能够别离在主过程中注册快捷键和在渲染过程中注册快捷键。
主过程注册快捷键
在主过程注册快捷键有两种形式,一种是利用 Menu
模块来模仿快捷键,二就是全局快捷键。
本地快捷键
咱们能够应用 Electron
中的 Menu
模块来配置键盘快捷键,只有在 app
处于焦点状态时才能够触发快捷键,应用比拟少。咱们在创立 Menuitem
时必须指定一个 accelerator
属性。
示例:
const { Menu, MenuItem } = require('electron');const menu = new Menu();menu.append(new MenuItem({ label: 'Print', accelerator: 'Ctrl+P', click: () => { console.log('打印材料') }}))
咱们还能够依据用户的操作系统配置不同的组合键:
accelerator: process.platform === 'darwin' ? 'Alt+Ctrl+I' : 'Ctrl+Shift+I'
全局快捷键
在应用程序没有键盘焦点时,咱们能够应用 globalshortcut
模块检测键盘事件。咱们来看上面这个例子。
示例:
上面代码中,咱们将开发者工具的快捷键设置为 Alt+B
:
// 引入electronconst {app, BrowserWindow,globalShortcut} = require('electron');let win;function createWindow() { // 创立浏览器窗口 win = new BrowserWindow({ width: 800, height: 400, webPreferences: { nodeIntegration: true, }, }); // 加载index.html文件 win.loadFile('../html/index.html'); // 主动关上开发者工具// win.webContents.openDevTools(); // 当 window 被敞开,这个事件会被触发 win.on('closed', () => { win = null; });}// Electron 会在初始化后并筹备,创立浏览器窗口时,调用这个函数app.on('ready', createWindow);// 当全副窗口敞开时退出app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); }});app.on('activate', () => { if (win === null) { createWindow(); }});// 注册快捷键app.on('ready', async () => { globalShortcut.register('Alt+B', function () { win.webContents.openDevTools(); }) createWindow();})
而后咱们运行 npm start
启动程序,只须要按下 Alt+B
键就能够关上开发者工具啦。
如果咱们不想要设置好的快捷键,也能够登记快捷键,代码如下所示:
app.on('ready', () => { // 登记快捷键 globalShortcut.register('Alt+B', () => { console.log('按下Alt+B'); }) // 登记所有快捷键 globalShortcut.unregisterAll();})
渲染过程注册快捷键
渲染过程注册快捷键也有两种形式,一个是利用浏览器监听键盘事件,另一个是利用第三方模块。
浏览器窗口的快捷方式
咱们能够利用浏览窗口监听键盘事件,这是一种惯例的形式,本人判断什么键按下:
window.addEventListener('keyup', doSomething, true);
第三个参数 true
的意思就是说监听器将始终在其余监听器之前收到按键,以防止其它监听器调用 stopPropagation()
。
利用第三方模块
如果咱们不想手动进行快捷键解析,能够应用一些库来进行高级的按键检测,比方 Mousetrap
。
首先咱们须要装置这个库,而后应用 Script
标签引入
npm install mousetrap --save
在 HTML
页面中引入 index.js
文件::
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>my_electron</title> </head> <body> <h2>你好,侠课岛!</h2> <script type="text/javascript" src=".js/index.js"></script> </body></html>
index.js
文件内容:
const Mousetrap = require('mousetrap');// 1:单个快捷键Mousetrap.bind('4', () => { console.log('4') })Mousetrap.bind('?', () => { console.log('显示快捷方式!') })Mousetrap.bind('esc', () => { console.log('escape') }, 'keyup')// 2:组合Mousetrap.bind('Alt+shift+k', () => { console.log('alt+shift+k') })// 3:将多个组合映射到同一回调Mousetrap.bind(['Alt+k', 'ctrl+k'], () => { console.log('Alt+k 或者 ctrl+k'); // 返回false以避免默认行为和进行事件冒泡 return false;})// Gmail款式序列 Mousetrap.bind('g i', () => { console.log('转到收件箱') });Mousetrap.bind('* a', () => { console.log('全选') });// konami code!Mousetrap.bind('up up down left right right left b a enter', () => { console.log('xkd_v3新版');})