7

我在监听事件时遇到问题,我可以监听完美运行的事件,但是我不能让它停止监听事件。我研究了一段时间,想出了一个方法,+ (void)removeMonitor:(id)eventMonitor,它说当我完成监听器时应该使用

但是当我尝试使用该方法时,就像这样

[NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseDownMask|NSKeyDownMask) handler:^(NSEvent *event) {
    [NSEvent removeMonitor:event];
}];

我不断收到“-[NSEvent invalidate]:无法识别的选择器发送到实例”的错误,我也对此进行了研究,我相信这意味着我正在覆盖正在使用的内存。但是我不知道如何解决这个问题。非常感谢任何建议或帮助!

更新感谢 JWWalker、Samir 和 Abizern,它现在可以工作了

//I made a global variable called eventHAndler

.h 文件

id eventHAndler

.m 文件

eventHAndler = [NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseDownMask|NSKeyDownMask) handler:^(NSEvent *event){
///code 
}];

/// created another method called stop. When called it stops the eventHAndler
- (IBAction)Stop:(id)sender 
{
    stop = 1;
    NSLog(@"inside stop method");
    [NSEvent removeMonitor:eventHAndler];
}
4

2 回答 2

19

你把错误的东西传递给removeMonitor:. 调用+[NSEvent addGlobalMonitorForEventsMatchingMask: handler:]返回一个称为事件处理程序对象的值。这就是可以传递给removeMonitor:.

于 2012-08-28T02:02:30.850 回答
0

According to: http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/EventOverview/MonitoringEvents/MonitoringEvents.html

They say:

A global event monitor looks for user-input events dispatched to applications other than the one in which it is installed. The monitor cannot modify an event or prevent its normal delivery. And it may only monitor key events if accessibility is enabled or if the application is trusted for accessibility.

So it is not possible says the man himself :P

于 2012-08-28T00:25:16.307 回答