我正在为 OS X 编写一个类似游戏的应用程序,需要知道在游戏循环期间是否按下了左箭头和右箭头。我还检查空格键是否按下。为此我实现了
-(void)keyDown:(NSEvent *)event;
-(void)keyUp:(NSEvent *)event
在我看来,并将每个键的状态存储在一些标志中。我还使用以下命令检查是否按下了命令按钮:
-(void)flagsChanged:(NSEvent *)event;
如果窗口不是主窗口(另一个窗口获得焦点)或放弃键(聚光灯打开),我会重置标志。我通过实现来做到这一点:
-(void)windowDidBecomeKey:(NSNotification *)notification;
-(void)windowDidResignKey:(NSNotification *)notification;
-(void)windowDidResignMain:(NSNotification *)notification;
-(void)windowDidBecomeMain:(NSNotification *)notification;
这几乎一直有效。如果我按命令,然后按空格键,聚光灯就会打开,并且我的应用程序会退出键。但是,如果我按住向左箭头键,然后首先按下并按住空格,然后命令,聚光灯将不会显示,但当我释放它们时,有时会丢失箭头键的按键事件。它不会每次都会发生,但是(可能取决于发布顺序),但在几次尝试中很容易重现。因此,该键会被卡住,直到下一次按下为止。
我的应用程序是否还进入了我不知道的另一种状态?如果不是,这种方法似乎有点脆弱。
是否有更可靠的方法来检查按键是否已按下(不需要安装记录器工具或在首选项中启用应用程序的可访问性)?
最佳答案
为此,我使用 NSEvent
的 addLocalMonitorForEventsMatchingMask:handler:
-静态方法。它在应用程序处于事件状态时工作。使用 addGlobalMonitor...
处理全局事件,但请注意您的应用程序可能会被 AppStore 拒绝。这里是一些代码示例。
id monitor=[NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:(NSEvent *)^(NSEvent *theEvent){
if (theEvent.keyCode==/*your key code*/) // you should check the key modifiers too
{
// your code here
}
return theEvent; // you may return the event to pass the key to the receiver or nil if no need
}];
// remove monitor
[NSEvent removeMonitor:monitor];
关于objective-c - 在 OS X 上丢失按键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28408333/