快捷键


Shortcut 代表一个全局键盘快捷键,也称为系统范围的热键。如果注册成功,即使您的应用程序没有焦点,它也能正常工作。

Shortcut 继承自 EventEmitter。每次用户按下注册的快捷键时,您的应用程序都会收到快捷键对象的 active 事件。

概述

var option = {
  key : "Ctrl+Shift+A",
  active : function() {
    console.log("Global desktop keyboard shortcut: " + this.key + " active."); 
  },
  failed : function(msg) {
    // :(, fail to register the |key| or couldn't parse the |key|.
    console.log(msg);
  }
};

// Create a shortcut with |option|.
var shortcut = new nw.Shortcut(option);

// Register global desktop shortcut, which can work without focus.
nw.App.registerGlobalHotKey(shortcut);

// If register |shortcut| successfully and user struck "Ctrl+Shift+A", |shortcut|
// will get an "active" event.

// You can also add listener to shortcut's active and failed event.
shortcut.on('active', function() {
  console.log("Global desktop keyboard shortcut: " + this.key + " active."); 
});

shortcut.on('failed', function(msg) {
  console.log(msg);
});

// Unregister the global desktop shortcut.
nw.App.unregisterGlobalHotKey(shortcut);

new Shortcut(option)

  • option {Object}
    • key {String} 快捷键的键组合,例如 "ctrl+shift+a"。有关详细信息,请参见 shortcut.key 属性。
    • active {Function} 可选 热键触发时的回调。有关详细信息,请参见 shortcut.active 属性。
    • failed {Function} 可选 注册热键失败时的回调。有关详细信息,请参见 shortcut.failed 属性。

创建新的 Shortcutoption 是一个包含 Shortcut 初始设置的对象。

shortcut.key

获取 Shortcutkey。它是一个字符串,用于指定快捷键,例如 "Ctrl+Alt+A"。该键由零个或多个修饰符和键盘上的一个组成。仅支持一个键代码。键代码不区分大小写。

支持的修饰符列表

  • Ctrl
  • Alt
  • Shift
  • CommandCommand 修饰符在 Mac 上映射到 Apple 键 (),在 Windows 和 Linux 上映射到 Windows 键。

支持的按键列表

  • 字母:A-Z
  • 数字:0-9
  • 功能键:F1-F24
  • 逗号
  • 句号
  • 制表符
  • Home / End / PageUp / PageDown / Insert / Delete
  • Up / Down / Left / Right
  • MediaNextTrack / MediaPlayPause / MediaPrevTrack / MediaStop
  • 逗号,
  • 句号.
  • 制表符\t
  • 反引号`
  • 回车\n
  • 减号-
  • 等号=
  • 反斜杠\
  • 分号;
  • 单引号'
  • 左方括号[
  • 右方括号]
  • Escape
  • DOM Level 3 W3C KeyboardEvent 代码值

单个按键,无修饰符

API App.registerGlobalHotKey() 可以支持应用程序拦截单个按键(例如 { key: "A"})。但用户将无法再正常使用“A”,直到应用程序取消注册它。但是,API 并不限制此用法,如果应用程序想要监听媒体键,它将很有用。
只有在你清楚自己在做什么时才使用零修饰符。

shortcut.active

获取或设置 Shortcutactive 回调。当用户按下快捷键时,将调用它。

shortcut.failed

*获取或设置 Shortcutfailed 回调。当应用程序传递无效的键或注册键失败时,将调用它。

事件:active

shortcut.active 相同

事件:failed

shortcut.failed 相同