跳至主要內容

鍵盤快捷鍵

概述

此功能可讓您為 Electron 應用程式設定本地和全域鍵盤快捷鍵。

範例

本地快捷鍵

本地鍵盤快捷鍵僅在應用程式處於焦點時觸發。若要設定本地鍵盤快捷鍵,您需要在 Menu 模組中建立 MenuItem 時指定 accelerator 屬性。

快速入門指南中的運作應用程式開始,更新 main.js

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

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

注意:在上面的程式碼中,您可以看到快捷鍵會根據使用者的作業系統而有所不同。對於 MacOS,它是 Alt+Cmd+I,而對於 Linux 和 Windows,它是 Alt+Shift+I

啟動 Electron 應用程式後,您應該會看到應用程式選單以及您剛定義的本地快捷鍵

Menu with a local shortcut

如果您按一下 Help 或按下定義的快捷鍵,然後開啟您執行 Electron 應用程式的終端機,您將會看到觸發 click 事件後產生的訊息:「Electron rocks!」。

全域快捷鍵

若要設定全域鍵盤快捷鍵,您需要使用 globalShortcut 模組來偵測鍵盤事件,即使應用程式沒有鍵盤焦點也一樣。

快速入門指南中的運作應用程式開始,更新 main.js

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

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

注意:在上面的程式碼中,CommandOrControl 組合在 macOS 上使用 Command,在 Windows/Linux 上使用 Control

啟動 Electron 應用程式後,如果您按下定義的按鍵組合,然後開啟您執行 Electron 應用程式的終端機,您將會看到 Electron 喜歡全域快捷鍵!

BrowserWindow 中的快捷鍵

使用 Web 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)

注意:第三個參數 true 表示監聽器將始終在其他監聽器之前接收按鍵,因此它們無法在其上呼叫 stopPropagation()

在主程序中攔截事件

在頁面中分派 keydownkeyup 事件之前,會發出 before-input-event 事件。它可以用來捕獲和處理選單中不可見的自訂快捷鍵。

快速入門指南中的運作應用程式開始,使用以下程式碼更新 main.js 檔案

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

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

啟動 Electron 應用程式後,如果您開啟您執行 Electron 應用程式的終端機,並按下 Ctrl+I 按鍵組合,您將會看到此按鍵組合已成功攔截。

使用第三方程式庫

如果您不想進行手動快捷鍵剖析,有一些程式庫可以進行進階按鍵偵測,例如 mousetrap。以下是在 Renderer 程序中執行 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')
})