如何在 Objective-C 中获取键盘状态而不引用 NSEvent
Objective-C 中是否可以在不引用 NSEvent 的情况下获取键盘状态?
一般来说,我不能使用 -[NSResponder flagsChanged:]
之类的 NSResponder
方法,但我需要知道当前是否按下了 Command 键。
Is it possible to get the keyboard state in Objective-C without referring to NSEvent
?
In general I can't use NSResponder
methods like -[NSResponder flagsChanged:]
but I need to know if the Command key is currently pressed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我仍然想知道为什么你不能使用 NSEvent,但无论如何我都会回答这个问题。也许您正在构建一个“命令行工具”并且仅与 Foundation 链接?您将必须至少再包含一个框架。如果您想链接到 AppKit,您可以(正如我在评论中提到的)使用
+[NSEvent modifierFlags]
;这是 NSEvent 上的一个类方法,因此您可以在任何地方使用它,而不需要访问单个事件,以获取修饰键的当前状态作为位掩码。该文档解释了 位掩码的含义。您还可以使用 Quartz 事件服务获取此信息。在这种情况下,您必须包含 ApplicationServices 框架*。 CGEventSource 函数 将为您提供 与您从
NSEvent
获得的相同位掩码:*如果您实际上正在编写 Cocoa 应用程序,那么这已经包含在内了——它是石英的一部分。
I'm still wondering why you can't use
NSEvent
, but I'm going to answer the question anyways. Perhaps you're building a "command-line tool" and are only linked against Foundation? You're going to have to include at least one more framework. If you want to link against AppKit, you can (as I mentioned in the comments) use+[NSEvent modifierFlags]
; this is a class method onNSEvent
, so you can use it anywhere, without needing to have access to an individual event, to get the current state of the modifier keys as a bitmask. The docs explain the meaning of the bitmask.You can also get this info using Quartz Event Services. In this case you have to include the ApplicationServices framework*. The CGEventSource functions will give you the same bitmask you get from
NSEvent
:*This is already included if you are, in fact, writing a Cocoa app -- it's part of Quartz.
当面向 macOS 10.12 或更高版本时,请使用此代码:
Use this code when targeting macOS 10.12 or newer: