使用 Electron 註冊鍵盤快捷鍵

使用 Electron 註冊鍵盤快捷鍵

此係列文章的應用示例已發佈於 GitHub: electron-api-demos-Zh_CN. 能夠 Clone 或下載後運行查看. 歡迎 Star .html

能夠使用 globalShortcutMenu 模塊定義鍵盤快捷鍵.git

在 Electron 中, 鍵盤快捷鍵被稱做加速器(Accelerator). 它們能夠分配到應用程序菜單中的操做上, 也能夠全局分配,因此即便你的應用程序沒有得到鍵盤焦點, 它們也能夠被觸發.github

在瀏覽器中查看 Menu, AcceleratorglobalShortcut API 的完整文檔.windows

註冊全局鍵盤快捷鍵

支持: Win, macOS, Linux | 進程: Mainapi

試一下這個示例, 在鍵盤上按下 Command或Control+Alt+K 快捷鍵.瀏覽器

即便應用程序沒有鍵盤焦點, 也會檢測到全局快捷鍵, 並且它們必須在應用程序的 ready 事件發出後註冊.app

主進程electron

const electron = require('electron')
const app = electron.app
const dialog = electron.dialog
const globalShortcut = electron.globalShortcut

app.on('ready', function () {
  globalShortcut.register('CommandOrControl+Alt+K', function () {
    dialog.showMessageBox({
      type: 'info',
      message: '成功!',
      detail: '你按下了一個全局註冊的快捷鍵綁定.',
      buttons: ['好的']
    })
  })
})

app.on('will-quit', function () {
  globalShortcut.unregisterAll()
})

高級技巧

避免覆蓋系統範圍的鍵盤快捷鍵.ide

註冊全局快捷方式時, 請務必注意目標操做系統中的現有默認值, 以避免覆蓋任何現有行爲.有關每一個操做系統鍵盤快捷鍵的概述, 請查看這些文檔:ui

若是這邊文章對您有幫助, 感謝 下方點贊 或 Star GitHub: electron-api-demos-Zh_CN 支持, 謝謝.

相關文章
相關標籤/搜索