Electron 鍵盤快捷鍵

2023-02-16 17:15 更新

概覽?

該功能允許你為 Electron 應(yīng)用程序配置應(yīng)用和全局鍵盤快捷鍵。

示例?

本地快捷鍵

應(yīng)用鍵盤快捷鍵僅在應(yīng)用程序被聚焦時觸發(fā)。 為了配置本地快捷鍵,你需要在創(chuàng)建?Menu?模塊中的?MenuItem?時指定accelerator屬性。

按照 快速入門 啟動一個應(yīng)用, 使用下面的代碼更新 main.js 文件:

 main.js index.html 
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()
  }
})
<!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>

DOCS/FIDDLES/FEATURES/KEYBOARD-SHORTCUTS/LOCAL (22.0.2)

Open in Fiddle

注意:在上面的代碼中,您可以看到基于用戶的操作系統(tǒng)的 accelerator 差異。 對于MacOS,是 ??Alt+Cmd+?I?,而對于Linux 和 Windows,則是 ?Alt+Shift+I?.

啟動 Electron 應(yīng)用程序后,你應(yīng)該看到應(yīng)用程序菜單以及您剛剛定義的本地快捷方式:


如果你點擊 Help 或按下定義的加速器,然后打開你運行的 Electron 應(yīng)用程序的終端。 將看到觸發(fā) click 事件后生成的消息:“Electron rocks!”

全局快捷鍵

要配置全局鍵盤快捷鍵, 您需要使用 ?globalShortcon? 模塊來檢測鍵盤事件,即使應(yīng)用程序沒有獲得鍵盤焦點。

按照 快速入門 啟動一個應(yīng)用, 使用下面的代碼更新 main.js 文件:

 main.js index.html 
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()
  }
})
<!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>

DOCS/FIDDLES/FEATURES/KEYBOARD-SHORTCUTS/GLOBAL (22.0.2)

Open in Fiddle

注:在上面的代碼中, ?CommandOrControl? 意指在 macOS 上使用 ?Command? ,在 Windows/Linux 上使用 ?Control? 。

啟動應(yīng)用后,如果你按下定義好的全局快捷鍵,你將在啟動的 Electron 應(yīng)用控制臺里面看到對應(yīng)的日志輸出

在瀏覽器窗口內(nèi)的快捷方式?

使用 web APIs

如果您想要在 ?BrowserWindow? 中處理鍵盤快捷鍵,你可以在渲染進程中使用 addEventListener() API來監(jiān)聽 kepup 和 keydown  DOM事件

 main.js index.html  renderer.js 
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron')
const path = require('path')

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)

DOCS/FIDDLES/FEATURES/KEYBOARD-SHORTCUTS/WEB-APIS (22.0.2)

Open in Fiddle

注意:第三個參數(shù) ?true? 表明了當(dāng)前監(jiān)聽器會持續(xù)在其它監(jiān)聽器之前接收按鍵按下事件,因此無法在其它監(jiān)聽器中調(diào)用 ?stopPropagation()?。

攔截主進程中的事件

在調(diào)度頁面中的keydownkeyup事件之前,會發(fā)出before-input-event事件。 它可以用于捕獲和處理在菜單中不可見的自定義快捷方式。

按照 快速入門 啟動一個應(yīng)用, 使用下面的代碼更新 main.js 文件:

 main.js index.html 
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()
    }
  })
})
<!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>

docs/fiddles/features/keyboard-shortcuts/interception-from-main

Open in Fiddle

在運行Electron應(yīng)用程序之后,如果你打開你運行Electron應(yīng)用的終端并按下 Ctrl+I 組合鍵,你會發(fā)現(xiàn)剛才按下的組合鍵被成功攔截了。

使用第三方庫

如果您不想手動進行快捷鍵解析,可以使用一些庫來進行高級的按鍵檢測。例如 mousetrap. 以下是在渲染進程中 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')
})


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號