问题描述
是否可以在没有引用NSEvent
的情况下在Objective-C中获得键盘状态?
Is it possible to get the keyboard state in Objective-C without referring to NSEvent
?
通常,我不能使用像-[NSResponder flagsChanged:]
这样的NSResponder
方法,但是我需要知道当前是否按下了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!");
}
您还可以使用石英事件服务.在这种情况下,您必须包括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.
这篇关于如何在Objective-C中获取键盘状态而不参考NSEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!