Skip to main content

键盘快捷键

🌐 Keyboard Shortcuts

加速器

🌐 Accelerators

加速键是可以在整个 Electron 应用中表示键盘快捷键的字符串。这些字符串可以包含多个修饰键和由 + 字符连接的单个键码。

🌐 Accelerators are strings that can be used to represent keyboard shortcuts throughout your Electron. These strings can contain multiple modifier keys and a single key code joined by the + character.

note

加速键 不区分大小写

可用修饰符

🌐 Available modifiers

  • Command(简称 Cmd
  • Control(简称 Ctrl
  • CommandOrControl(简称 CmdOrCtrl
  • Alt
  • Option
  • AltGr
  • Shift
  • Super(或别名 Meta

可用的键码

🌐 Available key codes

  • 09
  • AZ
  • F1F24
  • 各种标点符号:), !, @, #, $, %, ^, &, *, (, :, ;, :, +, =, <, ,, _, -, >, ., ?, /, ~, `, {, ], [, |, \, }, "
  • Plus
  • Space
  • Tab
  • Capslock
  • Numlock
  • Scrolllock
  • Backspace
  • Delete
  • Insert
  • Return(或别名 Enter
  • UpDownLeftRight
  • HomeEnd
  • PageUpPageDown
  • Escape(简称 Esc
  • VolumeUpVolumeDownVolumeMute
  • MediaNextTrackMediaPreviousTrackMediaStopMediaPlayPause
  • PrintScreen
  • 数字键盘按键
    • num0 - num9
    • numdec - 小数键
    • numadd - 小键盘 +
    • numsub - 小键盘 -
    • nummult - 小键盘 *
    • numdiv - 小键盘 ÷

跨平台修饰符

🌐 Cross-platform modifiers

许多修饰键加速器在不同操作系统之间映射到不同的键。

🌐 Many modifier accelerators map to different keys between operating systems.

修饰键macOSWindows 和 Linux
CommandOrControlCommand (⌘)Control
CommandCommand (⌘)不适用
ControlControl (^)Control
AltOption (⌥)Alt
OptionOption (⌥)不适用
Super (Meta)Command (⌘)Windows (⊞)
info
  • 在 Linux 和 Windows 上,Command 修饰符没有任何作用。通常,你应该改用 CommandOrControl 修饰符,它在 macOS 上表示 ⌘ Cmd,在 Linux 和 Windows 上表示 Ctrl。
  • 使用 Alt 代替 Option。⌥ Opt 键只存在于 macOS,而 Alt 会在所有平台上映射为相应的修饰符。

示例

🌐 Examples

以下是一些用于常见编辑操作的跨平台 Electron 加速器示例:

🌐 Here are some examples of cross-platform Electron accelerators for common editing operations:

  • 复制:CommandOrControl+C
  • 粘贴:CommandOrControl+V
  • 撤销:CommandOrControl+Z
  • 重做:CommandOrControl+Shift+Z

本地快捷键

🌐 Local shortcuts

本地 键盘快捷键仅在应用处于焦点时触发。这些快捷键映射到应用主菜单中的特定菜单项 应用菜单

要定义本地键盘快捷键,你需要在创建 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.

Opening a dialog via accelerator (local)
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”对话框。

tip

即使菜单项被隐藏,加速键也能使用。在 macOS 上,可以通过在构建 MenuItem 时设置 acceleratorWorksWhenHidden: false 来禁用此功能。

tip

在 Windows 和 Linux 上,可以将 MenuItemregisterAccelerator 属性设置为 false, 这样加速键在系统菜单中可见,但不可用。

全局快捷键

🌐 Global shortcuts

全局 键盘快捷键即使在应用未获得焦点时也能使用。要配置全局键盘快捷键,你可以使用 globalShortcut.register 函数来指定快捷键。

Opening a dialog via accelerator (global)
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.

Opening a dialog via accelerator (global)
const { globalShortcut } = require('electron/main')

globalShortcut.unregister('CommandOrControl+Alt+R')
warning

在 macOS 上,globalShortcut 有一个长期存在的 bug,它导致其无法与 QWERTY 之外的键盘布局一起使用 (electron/electron#19747)。

窗口内的快捷键

🌐 Shortcuts within a window

渲染进程中

🌐 In the renderer process

如果你想在 BaseWindow 中处理键盘快捷键,你可以在渲染进程中使用 addEventListener API 监听 keyupkeydown 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.

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()

在主进程中拦截事件

🌐 Intercepting events in the main process

before-input-event 事件会在渲染进程中派发 keydownkeyup 事件之前触发。它可以用于捕获和处理菜单中未显示的自定义快捷键。

🌐 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.

Intercepting the Ctrl+I event from the main process
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()
}
})
})