OS X 上丢失按键事件
Losing key-up event on OS X
我正在为 OS X 编写类似游戏的应用程序,需要知道在游戏循环期间是否按下了左右箭头。我还检查 space 栏是否已关闭。为此我实施
-(void)keyDown:(NSEvent *)event;
-(void)keyUp:(NSEvent *)event
在我看来,将每个键的状态存储在一些标志中。我还使用以下命令检查命令按钮是否被按下:
-(void)flagsChanged:(NSEvent *)event;
如果 window 不是主键(另一个 window 获得焦点)或辞职键(聚光灯打开),我会重置标志。我通过实施来做到这一点:
-(void)windowDidBecomeKey:(NSNotification *)notification;
-(void)windowDidResignKey:(NSNotification *)notification;
-(void)windowDidResignMain:(NSNotification *)notification;
-(void)windowDidBecomeMain:(NSNotification *)notification;
这几乎一直有效。如果我按命令然后 space,聚光灯打开并且我的应用程序退出密钥。但是,如果我按住左箭头键,然后先按住 space,然后命令,聚光灯将不会出现,但有时当我松开它们时,我会丢失箭头键的按键事件.它不会每次都发生,但(可能取决于发布顺序)但它很容易在几次尝试中重现。所以键会卡住直到下一次按下。
我的应用是否进入了我不知道的其他状态?如果不是,这种方法似乎有点脆弱。
是否有更可靠的方法来检查按键是否已按下(不需要安装记录器工具或在首选项中为应用程序启用辅助功能)?
为此,我使用了 NSEvent
的 addLocalMonitorForEventsMatchingMask:handler:
-static 方法。它在应用程序处于活动状态时工作。使用 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];
我正在为 OS X 编写类似游戏的应用程序,需要知道在游戏循环期间是否按下了左右箭头。我还检查 space 栏是否已关闭。为此我实施
-(void)keyDown:(NSEvent *)event;
-(void)keyUp:(NSEvent *)event
在我看来,将每个键的状态存储在一些标志中。我还使用以下命令检查命令按钮是否被按下:
-(void)flagsChanged:(NSEvent *)event;
如果 window 不是主键(另一个 window 获得焦点)或辞职键(聚光灯打开),我会重置标志。我通过实施来做到这一点:
-(void)windowDidBecomeKey:(NSNotification *)notification;
-(void)windowDidResignKey:(NSNotification *)notification;
-(void)windowDidResignMain:(NSNotification *)notification;
-(void)windowDidBecomeMain:(NSNotification *)notification;
这几乎一直有效。如果我按命令然后 space,聚光灯打开并且我的应用程序退出密钥。但是,如果我按住左箭头键,然后先按住 space,然后命令,聚光灯将不会出现,但有时当我松开它们时,我会丢失箭头键的按键事件.它不会每次都发生,但(可能取决于发布顺序)但它很容易在几次尝试中重现。所以键会卡住直到下一次按下。
我的应用是否进入了我不知道的其他状态?如果不是,这种方法似乎有点脆弱。
是否有更可靠的方法来检查按键是否已按下(不需要安装记录器工具或在首选项中为应用程序启用辅助功能)?
为此,我使用了 NSEvent
的 addLocalMonitorForEventsMatchingMask:handler:
-static 方法。它在应用程序处于活动状态时工作。使用 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];