键盘快捷键
快捷键组合
快捷键组合(Accelerators)是可以在整个 Electron 中用来表示键盘快捷键的字符串。这些字符串可以包含多个修饰键和一个由 + 字符连接的单个按键代码。
快捷键组合是不区分大小写的。
可用修饰键
Command(或简称Cmd)Control(或简称Ctrl)CommandOrControl(或简称CmdOrCtrl)AltOptionAltGrShiftSuper(或别名Meta)
可用按键代码
0到9A到ZF1到F24- 各种标点符号:
),!,@,#,$,%,^,&,*,(,:,;,:,+,=,<,,,_,-,>,.,?,/,~,`,{,],[,|,\,}," PlusSpaceTabCapslockNumlockScrolllockBackspaceDeleteInsertReturn(或别名Enter)Up,Down,Left和RightHome和EndPageUp和PageDownEscape(或简称Esc)VolumeUp,VolumeDown和VolumeMuteMediaNextTrack,MediaPreviousTrack,MediaStop和MediaPlayPausePrintScreen- 数字小键盘按键
num0-num9numdec- 小键盘小数点键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()
// 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”对话框。
即使菜单项被隐藏,快捷键组合仍然可以工作。在 macOS 上,可以通过在构建 MenuItem 时设置 acceleratorWorksWhenHidden: false 来禁用此功能。
在 Windows 和 Linux 上,可以将 MenuItem 的 registerAccelerator 属性设置为 false,以便在系统菜单中可见该快捷键组合但禁用它。
全局快捷键
全局键盘快捷键即使在应用程序失去焦点时也有效。要配置全局键盘快捷键,您可以使用 globalShortcut.register 函数来指定快捷键。
const { dialog, globalShortcut } = require('electron/main')
globalShortcut.register('CommandOrControl+Alt+R', () => {
dialog.showMessageBox({ message: 'Hello World!' })
})
要稍后注销快捷键,您可以使用 globalShortcut.unregisterAccelerator 函数。
const { globalShortcut } = require('electron/main')
globalShortcut.unregister('CommandOrControl+Alt+R')
在 macOS 上,globalShortcut 存在一个长期存在的 bug,它会导致它在 QWERTY 以外的键盘布局下无法工作(electron/electron#19747)。
窗口内的快捷键
在渲染器进程中
如果您想在 BaseWindow 中处理键盘快捷键,您可以在渲染器进程中使用 EventTarget.addEventListener API 来监听 keyup 和 keydown DOM 事件。
- 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://mdn.org.cn/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()。
在主进程中拦截事件
在将 keydown 和 keyup 事件分发到渲染器进程之前,会发出 before-input-event 事件。它可以用于捕获和处理菜单中不可见的自定义快捷键。
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()
}
})
})