In this section, we learn the keyboard shortcuts in Electron
In Electron
, keyboard shortcuts are called accelerators. They can be assigned to the operations in the application menu, and they can also be assigned globally, so even if your application does not get the keyboard core, they can also be triggered.
Electron
, there are two processes, the main process and the rendering process, so we can register the shortcut keys in the main process and the shortcut keys in the rendering process respectively.
Main process registration shortcut
There are two ways to register shortcut keys in the main process, one is to use the Menu
module to simulate shortcut keys, and the other is to use global shortcut keys.
Local shortcut
We can use Electron
in Menu
module to configure keyboard shortcuts, only app
when the in-focus state can trigger shortcuts, use less. We must specify a accelerator
attribute Menuitem
Example:
const { Menu, MenuItem } = require('electron');
const menu = new Menu();
menu.append(new MenuItem({
label: 'Print',
accelerator: 'Ctrl+P',
click: () => { console.log('打印资料') }
}))
We can also configure different key combinations according to the user's operating system:
accelerator: process.platform === 'darwin' ? 'Alt+Ctrl+I' : 'Ctrl+Shift+I'
Global shortcut keys
When the application does not have keyboard focus, we can use the globalshortcut
module to detect keyboard events. Let's look at the following example.
Example:
In the following code, we set the shortcut key of the developer tool to Alt+B
:
// 引入electron
const {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();
})
Then we run the npm start
startup program, just press the Alt+B
key to open the developer tools.
If we don't want to set the shortcut keys, we can also log out the shortcut keys, the code is as follows:
app.on('ready', () => {
// 注销快捷键
globalShortcut.register('Alt+B', () => {
console.log('按下Alt+B');
})
// 注销所有快捷键
globalShortcut.unregisterAll();
})
Render process registration shortcut
There are also two ways to register shortcut keys for the rendering process. One is to use the browser to monitor keyboard events, and the other is to use a third-party module.
Shortcut to the browser window
We can use the browser window to monitor keyboard events. This is a conventional way to determine which key is pressed:
window.addEventListener('keyup', doSomething, true);
The third parameter true
means that the listener will always receive keystrokes before other listeners to avoid other listeners from calling stopPropagation()
.
Utilize third-party modules
If we don't want to perform shortcut key analysis manually, we can use some libraries for advanced key detection, such as Mousetrap
.
First we need to install this library, and then use the Script
tag to import
npm install mousetrap --save
Introduce the index.js
file in the HTML
<!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
file content:
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新版');
})
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。