跳转到主内容

globalShortcut

在应用程序没有键盘焦点时,监听键盘事件。

Process: Main

globalShortcut 模块可以在操作系统中注册/注销全局快捷键, 以便可以为操作定制各种快捷键。

[!NOTE] The shortcut is global; it will work even if the app does not have the keyboard focus. This module cannot be used before the ready event of the app module is emitted. Please also note that it is also possible to use Chromium's GlobalShortcutsPortal implementation, which allows apps to bind global shortcuts when running within a Wayland session.

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

// 检查快捷键是否注册成功
console.log(globalShortcut.isRegistered('CommandOrControl+X'))
})

app.on('will-quit', () => {
// 注销快捷键
globalShortcut.unregister('CommandOrControl+X')

// 注销所有快捷键
globalShortcut.unregisterAll()
})

方法

globalShortcut 模块具有以下方法:

globalShortcut.register(accelerator, callback)

返回boolean - 快捷键注册是否成功

注册 accelerator 的全局快捷键。 当用户按下注册快捷键时, callback 会被调用。

如果指定的快捷键已经被其他应用程序注册掉, 调用会默默失败。 该特性由操作系统定义,因为操作系统不希望多个程序的全局快捷键互相冲突。

The following accelerators will not be registered successfully on macOS 10.14 Mojave unless the app has been authorized as a trusted accessibility client:

  • "Media Play/Pause"
  • "Media Next Track"
  • "Media Previous Track"
  • "Media Stop"

globalShortcut.registerAll(accelerators, callback)

注册多个全局快捷键。 当用户按下注册快捷键时, callback 会被调用。

如果定义的快捷键已经被其他应用占用,这个调用会失效。 该特性由操作系统定义,因为操作系统不希望多个程序的全局快捷键互相冲突。

The following accelerators will not be registered successfully on macOS 10.14 Mojave unless the app has been authorized as a trusted accessibility client:

  • "Media Play/Pause"
  • "Media Next Track"
  • "Media Previous Track"
  • "Media Stop"

globalShortcut.isRegistered(accelerator)

Returns boolean - 表示 accelerator 全局快捷键是否注册成功

当快捷键已经被其他应用程序注册时, 此调用将返回 false。 该特性由操作系统定义,因为操作系统不希望多个程序的全局快捷键互相冲突。

globalShortcut.unregister(accelerator)

注销 accelerator 的全局快捷键。

globalShortcut.unregisterAll()

注销所有的全局快捷键(清空该应用程序的全局快捷键)。