Question

I have a problem with listening for events, I can listen for events which works perfectly however I can't make it stop listening to events. I researched it for a while and came up with the a method, + (void)removeMonitor:(id)eventMonitor, that it says I should use when I'm done with the listener

But when I try to use the method, like so

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

I keep getting an error of "-[NSEvent invalidate]: unrecognized selector sent to instance" Which I researched as well, and I believe it means that I'm overwriting a memory that is being used. However I don't know how to solve this problem. Any suggestions, or help is greatly appreciated!

UPDATE Thanks to JWWalker, Samir and Abizern, it now works

//I made a global variable called eventHAndler

.h file

id eventHAndler

.m file

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];
}
Was it helpful?

Solution

You're passing the wrong thing to removeMonitor:. The call to +[NSEvent addGlobalMonitorForEventsMatchingMask: handler:] returns a value called an event handler object. That's what can be passed to removeMonitor:.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top