跳到主要內容

globalShortcut

偵測應用程式未取得鍵盤焦點時的鍵盤事件。

程序:主程序

globalShortcut 模組可以向作業系統註冊/取消註冊全域鍵盤快捷鍵,以便您可以自訂各種快捷鍵的操作。

注意: 快捷鍵是全域的;即使應用程式未取得鍵盤焦點,它也能運作。此模組在 app 模組的 ready 事件發出之前無法使用。

另請注意,也可以使用 Chromium 的 GlobalShortcutsPortal 實作,這允許應用程式在 Wayland 會議中執行時繫結全域快捷鍵。

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

// Enable usage of Portal's globalShortcuts. This is essential for cases when
// the app runs in a Wayland session.
app.commandLine.appendSwitch('enable-features', 'GlobalShortcutsPortal')

app.whenReady().then(() => {
// Register a 'CommandOrControl+X' shortcut listener.
const ret = globalShortcut.register('CommandOrControl+X', () => {
console.log('CommandOrControl+X is pressed')
})

if (!ret) {
console.log('registration failed')
}

// Check whether a shortcut is registered.
console.log(globalShortcut.isRegistered('CommandOrControl+X'))
})

app.on('will-quit', () => {
// Unregister a shortcut.
globalShortcut.unregister('CommandOrControl+X')

// Unregister all shortcuts.
globalShortcut.unregisterAll()
})

方法

globalShortcut 模組具有以下方法

globalShortcut.register(accelerator, callback)

傳回 boolean - 快捷鍵是否成功註冊。

註冊 accelerator 的全域快捷鍵。當使用者按下已註冊的快捷鍵時,會呼叫 callback

當快捷鍵已被其他應用程式佔用時,此呼叫將會靜默失敗。此行為是作業系統的預期行為,因為它們不希望應用程式爭奪全域快捷鍵。

除非應用程式已獲得授權成為受信任的輔助功能用戶端,否則以下快捷鍵將無法在 macOS 10.14 Mojave 上成功註冊

  • 「媒體播放/暫停」
  • 「媒體下一首曲目」
  • 「媒體上一首曲目」
  • 「媒體停止」

globalShortcut.registerAll(accelerators, callback)

註冊 accelerators 中所有 accelerator 項目的全域快捷鍵。當使用者按下任何已註冊的快捷鍵時,會呼叫 callback

當給定的快捷鍵已被其他應用程式佔用時,此呼叫將會靜默失敗。此行為是作業系統的預期行為,因為它們不希望應用程式爭奪全域快捷鍵。

除非應用程式已獲得授權成為受信任的輔助功能用戶端,否則以下快捷鍵將無法在 macOS 10.14 Mojave 上成功註冊

  • 「媒體播放/暫停」
  • 「媒體下一首曲目」
  • 「媒體上一首曲目」
  • 「媒體停止」

globalShortcut.isRegistered(accelerator)

傳回 boolean - 此應用程式是否已註冊 accelerator

當快捷鍵已被其他應用程式佔用時,此呼叫仍會傳回 false。此行為是作業系統的預期行為,因為它們不希望應用程式爭奪全域快捷鍵。

globalShortcut.unregister(accelerator)

取消註冊 accelerator 的全域快捷鍵。

globalShortcut.unregisterAll()

取消註冊所有全域快捷鍵。