How to get keyboard state in Objective-C without referring to NSEvent(如何在不参考 NSEvent 的情况下在 Objective-C 中获取键盘状态)
问题描述
是否可以在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 中获取键盘状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不参考 NSEvent 的情况下在 Objective-C 中获取
基础教程推荐
- 在 appComponent dagger 2 中动态添加测试模块? 2022-01-01
- 在 Android 模拟器中激活网络位置提供程序? 2022-01-01
- 在 iOS8 中无法获得正确的键盘高度值 2022-01-01
- 我的 UIImageView 的任务 2022-01-01
- 如何将多个组件添加到 PickerView? 2022-01-01
- 可可/目标C(OSX不是iOS)从子对象访问父对象 2022-01-01
- 新的@SystemApi 注解是什么意思,和@hide 有什么区别 2022-01-01
- 突出显示朗读文本(在 iPhone 的故事书类型应用程序中) 2022-01-01
- - (CGRect)convertRect:(CGRect)rect toView:(UIView *)view 如何工作 2022-01-01
- Android:STATE_SELECTED不工作 2022-01-01
