键盘快捷键
¥Keyboard Shortcuts
概述
¥Overview
此功能允许你为 Electron 应用配置本地和全局键盘快捷键。
¥This feature allows you to configure local and global keyboard shortcuts for your Electron application.
示例
¥Example
本地快捷方式
¥Local Shortcuts
仅当应用获得焦点时才会触发本地键盘快捷键。要配置本地键盘快捷键,你需要在 Menu 模块中创建 MenuItem 时指定 accelerator
属性。
¥Local keyboard shortcuts are triggered only when the application is focused.
To configure a local keyboard shortcut, you need to specify an accelerator
property when creating a MenuItem within the Menu module.
从 快速入门指南 的工作应用开始,将 main.js
更新为:
¥Starting with a working application from the
Quick Start Guide, update the main.js
to be:
- main.js
- index.html
const { app, BrowserWindow, Menu, MenuItem } = require('electron/main')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
const menu = new Menu()
menu.append(new MenuItem({
label: 'Electron',
submenu: [{
role: 'help',
accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Alt+Shift+I',
click: () => { console.log('Electron rocks!') }
}]
}))
Menu.setApplicationMenu(menu)
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
<p>Hit Alt+Shift+I on Windows, or Opt+Cmd+I on mac to see a message printed to the console.</p>
</body>
</html>
注意:在上面的代码中,你可以看到加速器根据用户的操作系统而有所不同。对于 MacOS,它是
Alt+Cmd+I
,而对于 Linux 和 Windows,它是Alt+Shift+I
。¥NOTE: In the code above, you can see that the accelerator differs based on the user's operating system. For MacOS, it is
Alt+Cmd+I
, whereas for Linux and Windows, it isAlt+Shift+I
.
启动 Electron 应用后,你应该会看到应用菜单以及刚刚定义的本地快捷方式:
¥After launching the Electron application, you should see the application menu along with the local shortcut you just defined:
如果你单击 Help
或按定义的加速键,然后打开运行 Electron 应用的终端,你将看到触发 click
事件后生成的消息:"Electron 摇滚!"。
¥If you click Help
or press the defined accelerator and then open the terminal
that you ran your Electron application from, you will see the message that was
generated after triggering the click
event: "Electron rocks!".
全局快捷键
¥Global Shortcuts
要配置全局键盘快捷键,即使应用没有键盘焦点,你也需要使用 globalShortcut 模块来检测键盘事件。
¥To configure a global keyboard shortcut, you need to use the globalShortcut module to detect keyboard events even when the application does not have keyboard focus.
从 快速入门指南 的工作应用开始,将 main.js
更新为:
¥Starting with a working application from the
Quick Start Guide, update the main.js
to be:
- main.js
- index.html
const { app, BrowserWindow, globalShortcut } = require('electron/main')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600
})
win.loadFile('index.html')
}
app.whenReady().then(() => {
globalShortcut.register('Alt+CommandOrControl+I', () => {
console.log('Electron loves global shortcuts!')
})
}).then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
<p>Hit Alt+Ctrl+I on Windows or Opt+Cmd+I on Mac to see a message printed to the console.</p>
</body>
</html>
注意:在上面的代码中,
CommandOrControl
组合在 macOS 上使用Command
,在 Windows/Linux 上使用Control
。¥NOTE: In the code above, the
CommandOrControl
combination usesCommand
on macOS andControl
on Windows/Linux.
启动 Electron 应用后,如果你按下定义的组合键,然后打开运行 Electron 应用的终端,你将看到 Electron 喜欢全局快捷键!
¥After launching the Electron application, if you press the defined key combination then open the terminal that you ran your Electron application from, you will see that Electron loves global shortcuts!
浏览器窗口内的快捷方式
¥Shortcuts within a BrowserWindow
使用网络 API
¥Using web APIs
如果你想处理 BrowserWindow 中的键盘快捷键,你可以使用 添加事件监听器() API 监听渲染器进程内的 keyup
和 keydown
DOM 事件。
¥If you want to handle keyboard shortcuts within a BrowserWindow, you can
listen for the keyup
and keydown
DOM events inside the
renderer process using the addEventListener() API.
- main.js
- index.html
- renderer.js
// Modules to control application life and create native browser window
const { app, BrowserWindow } = require('electron/main')
function createWindow () {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 800,
height: 600
})
// and load the index.html of the app.
mainWindow.loadFile('index.html')
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
if (process.platform !== 'darwin') app.quit()
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>Hello World!</title>
</head>
<body>
<h1>Hello World!</h1>
<p>Hit any key with this window focused to see it captured here.</p>
<div><span>Last Key Pressed: </span><span id="last-keypress"></span></div>
<script src="./renderer.js"></script>
</body>
</html>
function handleKeyPress (event) {
// You can put code here to handle the keypress.
document.getElementById('last-keypress').innerText = event.key
console.log(`You pressed ${event.key}`)
}
window.addEventListener('keyup', handleKeyPress, true)
注意:第三个参数
true
指示监听器始终会先于其他监听器接收按键,因此它们无法调用stopPropagation()
。¥Note: the third parameter
true
indicates that the listener will always receive key presses before other listeners so they can't havestopPropagation()
called on them.
在主进程中拦截事件
¥Intercepting events in the main process
before-input-event
事件在页面中调度 keydown
和 keyup
事件之前发出。它可用于捕获和处理菜单中不可见的自定义快捷方式。
¥The before-input-event
event
is emitted before dispatching keydown
and keyup
events in the page. It can
be used to catch and handle custom shortcuts that are not visible in the menu.
从 快速入门指南 的工作应用开始,使用以下行更新 main.js
文件:
¥Starting with a working application from the
Quick Start Guide, update the main.js
file with the
following lines:
- main.js
- index.html
const { app, BrowserWindow } = require('electron/main')
app.whenReady().then(() => {
const win = new BrowserWindow({ width: 800, height: 600 })
win.loadFile('index.html')
win.webContents.on('before-input-event', (event, input) => {
if (input.control && input.key.toLowerCase() === 'i') {
console.log('Pressed Control+I')
event.preventDefault()
}
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
<p>Hit Ctrl+I to see a message printed to the console.</p>
</body>
</html>
启动 Electron 应用后,如果打开运行 Electron 应用的终端并按 Ctrl+I
组合键,你将看到该组合键已成功拦截。
¥After launching the Electron application, if you open the terminal that you ran
your Electron application from and press Ctrl+I
key combination, you will
see that this key combination was successfully intercepted.
使用第三方库
¥Using third-party libraries
如果你不想进行手动快捷方式解析,可以使用一些可以进行高级按键检测的库,例如 mousetrap。下面是 Renderer 进程中运行的 mousetrap
的使用示例:
¥If you don't want to do manual shortcut parsing, there are libraries that do
advanced key detection, such as mousetrap. Below are examples of usage of the
mousetrap
running in the Renderer process:
Mousetrap.bind('4', () => { console.log('4') })
Mousetrap.bind('?', () => { console.log('show shortcuts!') })
Mousetrap.bind('esc', () => { console.log('escape') }, 'keyup')
// combinations
Mousetrap.bind('command+shift+k', () => { console.log('command shift k') })
// map multiple combinations to the same callback
Mousetrap.bind(['command+k', 'ctrl+k'], () => {
console.log('command k or control k')
// return false to prevent default behavior and stop event from bubbling
return false
})
// gmail style sequences
Mousetrap.bind('g i', () => { console.log('go to inbox') })
Mousetrap.bind('* a', () => { console.log('select all') })
// konami code!
Mousetrap.bind('up up down down left right left right b a enter', () => {
console.log('konami code')
})