键盘快捷键
加速器
加速器是可以在你的Electron中用来表示键盘快捷键的字符串。 这些字符串可以包含由 + 连接的多个修饰键和一个单一的键码。
[!NOTE] 加速器是 大小写不敏感 的。
可用的功能键
Command(缩写为Cmd)Control(缩写为Ctrl)CommandOrControl(缩写为CmdOrCtrl)AltOptionAltGrShiftSuper(别名为Meta)
可用的普通按键
0到9A到ZF1到F24- 各种标点符号包括:
),!,@,#,$,%,^,&,*,(,:,;,:,+,=,<,,,_,-,>,.,?,/,~,`,{,],[,|,\,}," PlusSpaceTab大写锁定(Capslock)数字锁定(Numlock)滚动锁定Backspace删除InsertReturn(等同于Enter)Up,Down,LeftandRightHome和EndPageUp和PageDownEscape(缩写为Esc)VolumeUp,VolumeDown和VolumeMuteMediaNextTrack、MediaPreviousTrack、MediaStop和MediaPlayPausePrintScreen- 小键盘按键
num1-num9-数字1-数字9numdec- 小数点numadd- 加号numsub- 减号nummult- 乘号numdiv- 除号
跨平台功能键
在不同的操作系统中,许多功能键加速器会映射到不同键。
| 功能键 | macOS | Windows 和 Linux |
|---|---|---|
CommandOrControl | Command (⌘) | Control |
Command | Command (⌘) | N/A |
Control | Control (^) | Control |
Alt | Option (⌥) | Alt |
Option | Option (⌥) | N/A |
Super (Meta) | Command (⌘) | Windows (⊞) |
- 在 Linux 和 Windows 上,
Command修饰符没有任何效果。 一般而言,您应该使用CommandOrControl修饰符来表示 macOS上的 ⌘ Cmd 和 Linux Windows 上的 Ctrl。 - 使用
Alt按键替代Option按键。 修饰符 ⌥ Opt 只存在于 macOS,但Alt会在所有平台都映射到正确的修饰符。
示例
以下是一些跨平台的 Electron 加速器通用编辑操作的例子:
- 复制:
CommandOrControl+C - 粘贴:
CommandOrControl+V - 撤销:
CommandOrControl+Z - 重做:
CommandOrControl+Shift+Z
本地快捷键
本地快捷键仅当应用获得焦点时才会触发。 这些快捷键映射到应用的主应用菜单中特定的菜单项。
如果要定义一个本地的键盘快捷键,你需要在创建一个 MenuItem 时配置 accelerator 属性。 然后,与该菜单项相关的 click 事件将在使用该加速器时触发。
const { dialog, Menu, MenuItem } = require('electron/main')
const menu = new Menu()
// 在 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 and Linux 上,把
MenuItem的registerAccelerator属性设置为false,可以使加速器在系统菜单中可见但不启用。
全局快捷键
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!' })
})
To later unregister a shortcut, you can use the globalShortcut.unregisterAccelerator function.
const { globalShortcut } = require('electron/main')
globalShortcut.unregister('CommandOrControl+Alt+R')
[!WARNING] On macOS, there's a long-standing bug with
globalShortcutthat 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.
- 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] The third parameter
trueindicates that the listener will always receive key presses before other listeners so they can't havestopPropagation()called on them.
拦截主进程中的事件
The before-input-event event is emitted before dispatching keydown and keyup events in the renderer 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()
}
})
})