键盘快捷键
¥Keyboard Shortcuts
加速器
¥Accelerators
加速器是字符串,可用于在整个 Electron 中表示键盘快捷键。这些字符串可以包含多个修饰键和一个由 +
字符连接的键码。
¥Accelerators are strings that can be used to represent keyboard shortcuts throughout your Electron.
These strings can contain multiple modifiers keys and a single key code joined by the +
character.
[!NOTE] 加速键不区分大小写。
¥[!NOTE] Accelerators are case-insensitive.
可用修饰符
¥Available modifiers
-
Command
(或简称Cmd
)¥
Command
(orCmd
for short) -
Control
(或简称Ctrl
)¥
Control
(orCtrl
for short) -
CommandOrControl
(或简称CmdOrCtrl
)¥
CommandOrControl
(orCmdOrCtrl
for short) -
Alt
-
Option
-
AltGr
-
Shift
-
Super
(或Meta
作为别名)¥
Super
(orMeta
as alias)
可用的键码
¥Available key codes
-
0
至9
¥
0
to9
-
A
至Z
¥
A
toZ
-
F1
至F24
¥
F1
toF24
-
各种标点符号:
)
、!
、@
、#
、$
、%
、^
、&
、*
、(
、:
、;
、:
、+
、=
、<
、,
、_
、-
、>
、.
、?
、/
、~
、```、{
、]
、[
、|
、\
、}
、"
¥Various Punctuation:
)
,!
,@
,#
,$
,%
,^
,&
,*
,(
,:
,;
,:
,+
,=
,<
,,
,_
,-
,>
,.
,?
,/
,~
,`
,{
,]
,[
,|
,\
,}
,"
-
Plus
-
Space
-
Tab
-
Capslock
-
Numlock
-
Scrolllock
-
Backspace
-
Delete
-
Insert
-
Return
(或Enter
作为别名)¥
Return
(orEnter
as alias) -
Up
、Down
、Left
和Right
¥
Up
,Down
,Left
andRight
-
Home
和End
¥
Home
andEnd
-
PageUp
和PageDown
¥
PageUp
andPageDown
-
Escape
(或简称Esc
)¥
Escape
(orEsc
for short) -
VolumeUp
、VolumeDown
和VolumeMute
¥
VolumeUp
,VolumeDown
andVolumeMute
-
MediaNextTrack
、MediaPreviousTrack
、MediaStop
和MediaPlayPause
¥
MediaNextTrack
,MediaPreviousTrack
,MediaStop
andMediaPlayPause
-
PrintScreen
-
数字键盘按键
¥NumPad Keys
-
num0
-num9
-
numdec
- 小数键¥
numdec
- decimal key -
numadd
- 数字键盘+
键¥
numadd
- numpad+
key -
numsub
- 数字键盘-
键¥
numsub
- numpad-
key -
nummult
- 数字键盘*
键¥
nummult
- numpad*
key -
numdiv
- 数字键盘÷
键¥
numdiv
- numpad÷
key
-
跨平台修饰符
¥Cross-platform modifiers
许多修饰键加速器在不同操作系统之间映射到不同的键。
¥Many modifier accelerators map to different keys between operating systems.
修饰符 | 苹果系统 | Windows 和 Linux |
---|---|---|
CommandOrControl | Command (⌘) | Control |
Command | Command (⌘) | 不适用 |
Control | Control (^) | Control |
Alt | 选项 (⌥) | Alt |
Option | 选项 (⌥) | 不适用 |
Super (Meta ) | Command (⌘) | Windows (⊞) |
-
在 Linux 和 Windows 上,
Command
修饰符没有任何效果。通常,你应该使用CommandOrControl
修饰符,它在 macOS 上代表 ⌘ Cmd,在 Linux 和 Windows 上代表 Ctrl。¥On Linux and Windows, the
Command
modifier does not have any effect. In general, you should use theCommandOrControl
modifier instead, which represents ⌘ Cmd on macOS and Ctrl on Linux and Windows. -
使用
Alt
代替Option
。⌥ Opt 键仅在 macOS 上存在,而Alt
在所有平台上都会映射到相应的修饰符。¥Use
Alt
instead ofOption
. The ⌥ Opt key only exists on macOS, whereas theAlt
will map to the appropriate modifier on all platforms.
示例
¥Examples
以下是一些用于常见编辑操作的跨平台 Electron 加速器示例:
¥Here are some examples of cross-platform Electron accelerators for common editing operations:
-
复制:
CommandOrControl+C
¥Copy:
CommandOrControl+C
-
粘贴:
CommandOrControl+V
¥Paste:
CommandOrControl+V
-
撤消:
CommandOrControl+Z
¥Undo:
CommandOrControl+Z
-
重做:
CommandOrControl+Shift+Z
¥Redo:
CommandOrControl+Shift+Z
本地快捷键
¥Local shortcuts
仅当应用获得焦点时才会触发本地键盘快捷键。这些快捷键映射到应用主 应用菜单 中的特定菜单项。
¥Local keyboard shortcuts are triggered only when the application is focused. These shortcuts map to specific menu items within the app's main application menu.
要定义本地键盘快捷键,你需要在创建 MenuItem 时配置 accelerator
属性。然后,使用该加速键时将触发与该菜单项关联的 click
事件。
¥To define a local keyboard shortcut, you need to configure the accelerator
property when creating
a MenuItem. Then, the click
event associated to that menu item will trigger
upon using that accelerator.
const { dialog, Menu, MenuItem } = require('electron/main')
const menu = new Menu()
// The first submenu needs to be the app menu on macOS
if (process.platform === 'darwin') {
const appMenu = new MenuItem({ role: 'appMenu' })
menu.append(appMenu)
}
const submenu = Menu.buildFromTemplate([{
label: 'Open a Dialog',
click: () => dialog.showMessageBox({ message: 'Hello World!' }),
accelerator: 'CommandOrControl+Alt+R'
}])
menu.append(new MenuItem({ label: 'Custom Menu', submenu }))
Menu.setApplicationMenu(menu)
在上面的示例中,在 macOS 上按下 ⌘ Cmd+⌥ Opt+R 或在其他平台上按下 Ctrl+Alt+R 时,将打开一个原生 "Hello World" 对话框。
¥In the above example, a native "Hello World" dialog will open when pressing ⌘ Cmd+⌥ Opt+R on macOS or Ctrl+Alt+R on other platforms.
[!提示] 即使菜单项被隐藏,加速器仍可工作。在 macOS 上,可以通过在构建
MenuItem
时设置acceleratorWorksWhenHidden: false
来禁用此功能。¥[!TIP] Accelerators can work even when menu items are hidden. On macOS, this feature can be disabled by setting
acceleratorWorksWhenHidden: false
when building aMenuItem
.
[!TIP] 在 Windows 和 Linux 上,可以将
MenuItem
的registerAccelerator
属性设置为false
,以便加速器在系统菜单中可见但不启用。¥[!TIP] On Windows and Linux, the
registerAccelerator
property of theMenuItem
can be set tofalse
so that the accelerator is visible in the system menu but not enabled.
全局快捷键
¥Global shortcuts
即使你的应用失去焦点,全局键盘快捷键也能正常工作。要配置全局键盘快捷键,你可以使用 globalShortcut.register
函数指定快捷键。
¥Global keyboard shortcuts work even when your app is out of focus. To configure a global keyboard
shortcut, you can use the globalShortcut.register
function to specify shortcuts.
const { dialog, globalShortcut } = require('electron/main')
globalShortcut.register('CommandOrControl+Alt+R', () => {
dialog.showMessageBox({ message: 'Hello World!' })
})
要稍后注销快捷键,你可以使用 globalShortcut.unregisterAccelerator
函数。
¥To later unregister a shortcut, you can use the globalShortcut.unregisterAccelerator
function.
const { globalShortcut } = require('electron/main')
globalShortcut.unregister('CommandOrControl+Alt+R')
[!WARNING] 在 macOS 上,
globalShortcut
存在一个长期存在的错误,导致它无法与 QWERTY(electron/electron#19747)以外的键盘布局配合使用。¥[!WARNING] On macOS, there's a long-standing bug with
globalShortcut
that prevents it from working with keyboard layouts other than QWERTY (electron/electron#19747).
窗口内的快捷键
¥Shortcuts within a window
渲染进程中
¥In the renderer process
如果你想在 BaseWindow 中处理键盘快捷键,你可以使用 addEventListener API 在渲染器进程中监听 keyup
和 keydown
DOM 事件。
¥If you want to handle keyboard shortcuts within a BaseWindow, 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)
[!NOTE] 第三个参数
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 renderer process. It can
be used to catch and handle custom shortcuts that are not visible in the menu.
const { app, BrowserWindow } = require('electron/main')
app.whenReady().then(() => {
const win = new BrowserWindow()
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()
}
})
})