Matt S. is correct that if you can use the NSEvent
API to get the mouse location. However, you don't have to poll in order to continuously get coordinates. You can use a CGEventTap
instead:
- (void) startEventTap {
//eventTap is an ivar on this class of type CFMachPortRef
eventTap = CGEventTapCreate(kCGHIDEventTap, kCGHeadInsertEventTap, kCGEventTapOptionListenOnly, kCGEventMaskForAllEvents, myCGEventCallback, NULL);
CGEventTapEnable(eventTap, true);
}
CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
if (type == kCGEventMouseMoved) {
NSLog(@"%@", NSStringFromPoint([NSEvent mouseLocation]));
}
return event;
}
This way, your function myCGEventCallback
will fire every time the mouse moves (regardless of whether your app is frontmost or not), without you having to poll for the information. Don't forget to CGEventTapEnable(eventTap, false)
and CFRelease(eventTap)
when you're done.