鍵盤快捷鍵
概述
此功能可讓您為 Electron 應用程式設定本地和全域鍵盤快捷鍵。
範例
本地快捷鍵
本地鍵盤快捷鍵僅在應用程式處於焦點時觸發。若要設定本地鍵盤快捷鍵,您需要在 Menu 模組中建立 MenuItem 時指定 accelerator
屬性。
從快速入門指南中的運作應用程式開始,更新 main.js
為
- main.js
- index.html
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()
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
<p>Hit Alt+Shift+I on Windows, or Opt+Cmd+I on mac to see a message printed to the console.</p>
</body>
</html>
注意:在上面的程式碼中,您可以看到快捷鍵會根據使用者的作業系統而有所不同。對於 MacOS,它是
Alt+Cmd+I
,而對於 Linux 和 Windows,它是Alt+Shift+I
。
啟動 Electron 應用程式後,您應該會看到應用程式選單以及您剛定義的本地快捷鍵
如果您按一下 Help
或按下定義的快捷鍵,然後開啟您執行 Electron 應用程式的終端機,您將會看到觸發 click
事件後產生的訊息:「Electron rocks!」。
全域快捷鍵
若要設定全域鍵盤快捷鍵,您需要使用 globalShortcut 模組來偵測鍵盤事件,即使應用程式沒有鍵盤焦點也一樣。
從快速入門指南中的運作應用程式開始,更新 main.js
為
- main.js
- index.html
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()
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
<p>Hit Alt+Ctrl+I on Windows or Opt+Cmd+I on Mac to see a message printed to the console.</p>
</body>
</html>
注意:在上面的程式碼中,
CommandOrControl
組合在 macOS 上使用Command
,在 Windows/Linux 上使用Control
。
啟動 Electron 應用程式後,如果您按下定義的按鍵組合,然後開啟您執行 Electron 應用程式的終端機,您將會看到 Electron 喜歡全域快捷鍵!
BrowserWindow 中的快捷鍵
使用 Web API
如果您想在 BrowserWindow 中處理鍵盤快捷鍵,您可以使用 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://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)
注意:第三個參數
true
表示監聽器將始終在其他監聽器之前接收按鍵,因此它們無法在其上呼叫stopPropagation()
。
在主程序中攔截事件
在頁面中分派 keydown
和 keyup
事件之前,會發出 before-input-event
事件。它可以用來捕獲和處理選單中不可見的自訂快捷鍵。
從快速入門指南中的運作應用程式開始,使用以下程式碼更新 main.js
檔案
- main.js
- index.html
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()
}
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
<h1>Hello World!</h1>
<p>Hit Ctrl+I to see a message printed to the console.</p>
</body>
</html>
啟動 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')
})