Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addGlobalMonitorForEventsMatchingMask only returning mouse position

I'm trying to learn to code for the Mac. I've been a Java guy for a while, so I hope the problem I'm running into is a simple misunderstanding of Cocoa.

I've got the following code:

-(IBAction)beginEventMonitor:(id)sender {
  _eventMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseUpMask)
  handler:^(NSEvent *incomingEvent) {
    //NSWindow *targetWindowForEvent = [incomingEvent window];
    NSLog(@"Got a mouse click event at %@", NSStringFromPoint([incomingEvent locationInWindow]));
    }];
}

-(IBAction)stopEventMonitor:(id)sender {
  if (_eventMonitor) {
    [NSEvent removeMonitor:_eventMonitor];
    _eventMonitor = nil;
  }
}

This is a simple hook to tell me when a mouse click happens at a global level. The handler is working, but the contents of the incomingEvent don't seem to be set to anything. The only useful information that I can find is the location of the mouse at the time of the click, and the windowId of the window that was clicked in.

Shouldn't I be able to get more information? Am I not setting up the monitor correctly? I'd really like to be able to know which window was clicked in, but I can't even find a way to turn the mouse location or windowId into something useful.

like image 924
Chad Avatar asked Jan 15 '11 22:01

Chad


1 Answers

You can retrieve more information about the window using the CGWindow APIs (new in Leopard), for example:

CGWindowID windowID = (CGWindowID)[incomingEvent windowNumber];
CFArrayRef a = CFArrayCreate(NULL, (void *)&windowID, 1, NULL);
NSArray *windowInfos = (NSArray *)CGWindowListCreateDescriptionFromArray(a);
CFRelease(a);
if ([windowInfos count] > 0) {
    NSDictionary *windowInfo = [windowInfos objectAtIndex:0];
    NSLog(@"Name:  %@", [windowInfo objectForKey:(NSString *)kCGWindowName]);
    NSLog(@"Owner: %@", [windowInfo objectForKey:(NSString *)kCGWindowOwnerName]);
    //etc.
}
[windowInfos release];

There's lots of information there (look in CGWindow.h or refer to the docs for available keys). There are also functions to create screenshots of just one window (which even works if it's partially covered by another window), cool stuff!

like image 147
omz Avatar answered Sep 24 '22 01:09

omz