如何在不参考 NSEvent 的情况下在 Objective-C 中获取键盘状态

How to get keyboard state in Objective-C without referring to NSEvent(如何在不参考 NSEvent 的情况下在 Objective-C 中获取键盘状态)
本文介绍了如何在不参考 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 中获取键盘状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

No resource found that matches the given name: attr #39;android:keyboardNavigationCluster#39;. when updating to Support Library 26.0.0(找不到与给定名称匹配的资源:attr android:keyboardNavigationCluster.更新到支持库 26.0.0 时) - IT屋-程序员软
How to resize UITextView on iOS when a keyboard appears?(出现键盘时如何在iOS上调整UITextView的大小?)
How to reliably detect if an external keyboard is connected on iOS 9?(如何可靠地检测 iOS 9 上是否连接了外部键盘?)
How to mimic Keyboard animation on iOS 7 to add quot;Donequot; button to numeric keyboard?(如何在 iOS 7 上模拟键盘动画以添加“完成数字键盘的按钮?)
How do I dismiss the iOS keyboard?(如何关闭 iOS 键盘?)
Is possible to simulate touch event using an external keyboard on ios jailbroken?(是否可以在 ios 越狱后使用外部键盘模拟触摸事件?)