跳转到主内容

键盘快捷键

Accelerators

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] Accelerators are case-insensitive.

可用的功能键

  • Command (缩写为Cmd)
  • Control (缩写为Ctrl)
  • CommandOrControl (缩写为 CmdOrCtrl)
  • Alt
  • Option
  • AltGr
  • Shift
  • Super (or Meta as alias)

可用的普通按键

  • 09
  • AZ
  • F1F24
  • 各种标点符号包括:), !, @, #, $, %, ^, &, *, (, :, ;, :, +, =, <, ,, _, -, >, ., ?, /, ~, `, {, ], [, |, \, }, "
  • Plus
  • Space
  • Tab
  • 大写锁定(Capslock)
  • 数字锁定(Numlock)
  • 滚动锁定
  • Backspace
  • 删除
  • Insert
  • Return (等同于 Enter)
  • Up, Down, Left and Right
  • HomeEnd
  • PageUpPageDown
  • Escape (缩写为 Esc)
  • VolumeUp, VolumeDownVolumeMute
  • MediaNextTrackMediaPreviousTrackMediaStopMediaPlayPause
  • PrintScreen
  • 小键盘按键
    • num1-num9 -数字1-数字9
    • numdec - 小数点
    • numadd - 加号
    • numsub - 减号
    • nummult - 乘号
    • numdiv - 除号

Cross-platform modifiers

Many modifier accelerators map to different keys between operating systems.

ModifiermacOSWindows 和 Linux
CommandOrControlCommand (⌘)控制
命令Command (⌘)N/A
控制Control (^)控制
AltOption (⌥)Alt
OptionOption (⌥)N/A
Super (Meta)Command (⌘)Windows (⊞)
info
  • On Linux and Windows, the Command modifier does not have any effect. In general, you should use the CommandOrControl modifier instead, which represents ⌘ Cmd on macOS and Ctrl on Linux and Windows.
  • 使用 Alt按键替代 Option按键。 The ⌥ Opt key only exists on macOS, whereas the Alt will map to the appropriate modifier on all platforms.

示例

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

  • Copy: CommandOrControl+C
  • Paste: CommandOrControl+V
  • Undo: CommandOrControl+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.

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)

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.

[!TIP] Accelerators can work even when menu items are hidden. On macOS, this feature can be disabled by setting acceleratorWorksWhenHidden: false when building a MenuItem.

[!TIP] On Windows and Linux, the registerAccelerator property of the MenuItem can be set to false so that the accelerator is visible in the system menu but not enabled.

Global shortcuts

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.

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

globalShortcut.register('CommandOrControl+Alt+R', () => {
dialog.showMessageBox({ message: 'Hello World!' })
})

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] 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

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] The third parameter true indicates that the listener will always receive key presses before other listeners so they can't have stopPropagation() called on them.

拦截主进程中的事件

The before-input-event event is emitted before dispatching keydown and keyup events in the renderer process. 它可以用于捕获和处理在菜单中不可见的自定义快捷方式。

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