是否可以在Objective-C中不参考NSEvent
获取键盘状态?
Is it possible to get the keyboard state in Objective-C without referring to NSEvent
?
一般我不能使用 NSResponder
方法,如 -[NSResponder flagsChanged:]
但我需要知道当前是否按下了 Command 键.
In general I can't use NSResponder
methods like -[NSResponder flagsChanged:]
but I need to know if the Command key is currently pressed.
我仍然想知道为什么你不能使用 NSEvent
,但我还是要回答这个问题.也许你正在构建一个命令行工具"并且只与 Foundation 相关联?你将不得不包含至少一个更多的框架.如果你想链接到 AppKit,你可以(正如我在评论中提到的)使用 +[NSEvent modifierFlags]
;这是 NSEvent
上的类方法,因此您可以在任何地方使用它,而无需访问单个事件,以获取修饰键的当前状态作为位掩码.文档解释了 位掩码的含义.
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 on NSEvent
, 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.
if( NSCommandKeyMask & [NSEvent modifierFlags] ){
NSLog(@"Oh, yeah!");
}
您也可以使用 获取此信息Quartz 事件服务.在这种情况下,您必须包含 ApplicationServices 框架*.CGEventSource 函数 将为您提供 相同的位掩码 你从 NSEvent
得到:
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
:
CGEventFlags theFlags;
theFlags = CGEventSourceFlagsState(kCGEventSourceStateHIDSystemState);
if( kCGEventFlagMaskCommand & theFlags ){
NSLog(@"Uh huh!");
}
<小时>
*如果您实际上正在编写一个 Cocoa 应用程序,那么它已经包含在内——它是 Quartz 的一部分.
*This is already included if you are, in fact, writing a Cocoa app -- it's part of Quartz.
这篇关于如何在不参考 NSEvent 的情况下在 Objective-C 中获取键盘状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!