Skip to main content

Keyboard Shortcuts键盘快捷键

Overview概述

This feature allows you to configure local and global keyboard shortcuts for your Electron application.此功能允许您为Electron应用程序配置本地和全局键盘快捷键。

Example示例

Local Shortcuts本地快捷方式

Local keyboard shortcuts are triggered only when the application is focused. 本地键盘快捷键仅在应用程序聚焦时触发。To configure a local keyboard shortcut, you need to specify an accelerator property when creating a MenuItem within the Menu module.要配置本地键盘快捷键,需要在Menu模块中创建MenuItem时指定加速器属性。

Starting with a working application from the Quick Start Guide, update the main.js file with the following lines:快速入门指南中的工作应用程序开始,使用以下行更新main.js文件:

const { app, BrowserWindow, Menu, MenuItem } = require('electron')

function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
})

win.loadFile('index.html')
}

const menu = new Menu()
menu.append(new MenuItem({
label: 'Electron',
submenu: [{
role: 'help',
accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Alt+Shift+I',
click: () => { console.log('Electron rocks!') }
}]
}))

Menu.setApplicationMenu(menu)

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})

app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})

NOTE: In the code above, you can see that the accelerator differs based on the user's operating system. 注意:在上面的代码中,您可以看到加速器根据用户的操作系统而有所不同。For MacOS, it is Alt+Cmd+I, whereas for Linux and Windows, it is Alt+Shift+I.对于MacOS,它是Alt+Cmd+I,而对于Linux和Windows,它是Alt+Shift+I

After launching the Electron application, you should see the application menu along with the local shortcut you just defined:启动Electron应用程序后,您应该看到应用程序菜单以及刚刚定义的本地快捷方式:

Menu with a local shortcut

If you click Help or press the defined accelerator and then open the terminal that you ran your Electron application from, you will see the message that was generated after triggering the click event: "Electron rocks!".如果单击Help或按下定义的加速器,然后打开运行Electron应用程序的终端,您将看到触发click事件后生成的消息:“Electron rocks!”。

Global Shortcuts全球快捷键

To configure a global keyboard shortcut, you need to use the globalShortcut module to detect keyboard events even when the application does not have keyboard focus.要配置全局键盘快捷键,您需要使用globalShortcut模块来检测键盘事件,即使应用程序没有键盘焦点。

Starting with a working application from the Quick Start Guide, update the main.js file with the following lines:快速入门指南中的工作应用程序开始,使用以下行更新mainjs文件:

const { app, BrowserWindow, globalShortcut } = require('electron')

function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
})

win.loadFile('index.html')
}

app.whenReady().then(() => {
globalShortcut.register('Alt+CommandOrControl+I', () => {
console.log('Electron loves global shortcuts!')
})
}).then(createWindow)

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})

app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})

NOTE: In the code above, the CommandOrControl combination uses Command on macOS and Control on Windows/Linux.注意:在上面的代码中,CommandOrControl组合使用macOS上的Command和Windows/Linux上的Control

After launching the Electron application, if you press the defined key combination then open the terminal that you ran your Electron application from, you will see that Electron loves global shortcuts!启动Electron应用程序后,如果您按下定义的组合键,然后打开运行Electron应用程序的终端,您将看到Electron喜欢全局快捷方式!

Shortcuts within a BrowserWindowBrowserWindow中的快捷键

Using web APIs使用web API

If you want to handle keyboard shortcuts within a BrowserWindow, you can listen for the keyup and keydown DOM events inside the renderer process using the addEventListener() API.如果要在BrowserWindow中处理键盘快捷键,可以使用addEventListener()API在渲染器进程中侦听keyupkeydown DOM事件

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.注意:第三个参数true表示监听器将始终在其他监听器之前接收按键,因此不能对其调用stopPropagation()

Intercepting events in the main process拦截主进程中的事件

The before-input-event event is emitted before dispatching keydown and keyup events in the page. before-input-event事件是在页面中调度keydownkeyup事件之前发出的。It can be used to catch and handle custom shortcuts that are not visible in the menu.它可用于捕获和处理菜单中不可见的自定义快捷方式。

Starting with a working application from the Quick Start Guide, update the main.js file with the following lines:快速入门指南中的工作应用程序开始,使用以下行更新main.js文件:

const { app, BrowserWindow } = require('electron')

app.whenReady().then(() => {
const win = new BrowserWindow({ width: 800, height: 600 })

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

After launching the Electron application, if you open the terminal that you ran your Electron application from and press Ctrl+I key combination, you will see that this key combination was successfully intercepted.启动Electron应用程序后,如果打开运行Electron应用程序的终端并按Ctrl+I组合键,您将看到该组合键被成功拦截。

Using third-party libraries使用第三方库

If you don't want to do manual shortcut parsing, there are libraries that do advanced key detection, such as mousetrap. 如果不想进行手动快捷方式解析,可以使用一些库进行高级键检测,如mousetrapBelow are examples of usage of the mousetrap running in the Renderer process:以下是在渲染器进程中运行的mousetrap的使用示例:

Mousetrap.bind('4', () => { console.log('4') })
Mousetrap.bind('?', () => { console.log('show shortcuts!') })
Mousetrap.bind('esc', () => { console.log('escape') }, 'keyup')

// combinations
Mousetrap.bind('command+shift+k', () => { console.log('command shift k') })

// map multiple combinations to the same callback
Mousetrap.bind(['command+k', 'ctrl+k'], () => {
console.log('command k or control k')

// return false to prevent default behavior and stop event from bubbling
return false
})

// gmail style sequences
Mousetrap.bind('g i', () => { console.log('go to inbox') })
Mousetrap.bind('* a', () => { console.log('select all') })

// konami code!
Mousetrap.bind('up up down down left right left right b a enter', () => {
console.log('konami code')
})