【问题标题】:Listening for global keyboard shortcuts in MacOS application在 MacOS 应用程序中侦听全局键盘快捷键
【发布时间】:2017-05-23 22:39:26
【问题描述】:
我创建了一个小型 Swift 应用程序,它位于菜单栏中(时钟结束)。我想让应用程序在后台侦听键盘快捷键,然后让它调用 Web API 以获取一些信息。除了全局键盘快捷键部分之外,我一切正常。
经过一番搜索,我发现了NSEvent.addGlobalMonitorForEvents。这最初看起来很有希望。我能够让我的应用程序接收所有按键并过滤掉除我正在寻找的那个之外的所有内容。经过 Apple 文档的一些试验和确认后,我发现这种机制实际上并没有“处理”该事件。按键仍然被发送到前台应用程序,这在这种情况下是不可取的。
是否有更好/正确的方法让我的应用程序响应全局键盘快捷键?理想情况下,这在不使用任何第三方 API 或应用程序的情况下是可能的,尽管它不会破坏交易。
【问题讨论】:
标签:
swift3
keyboard-shortcuts
macos-sierra
【解决方案1】:
我创建了一个Swift package,它让添加全局键盘快捷键变得超级简单。
import SwiftUI
import KeyboardShortcuts
// Declare the shortcut for strongly-typed access
extension KeyboardShortcuts.Name {
static let toggleUnicornMode = Self("toggleUnicornMode")
}
@main
final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
// Register the listener
KeyboardShortcuts.onKeyUp(for: .toggleUnicornMode) { [self] in
isUnicornMode.toggle()
}
}
}
// You also need to let the user choose a shortcut in the preferences
struct PreferencesView: View {
var body: some View {
HStack(alignment: .firstTextBaseline) {
Text("Toggle Unicorn Mode:")
KeyboardShortcuts.Recorder(for: .toggleUnicornMode)
}
}
}
如果您查看codebase(需要大量陈旧代码),您就会明白为什么不想从头开始实现它。