views:

198

answers:

2

How can I get in Mac OS X "global" mouse position - I mean how can I in cocoa/cf/whatever find out cursor position even if it's outside the window, and even if my window is inactive?

I know it's somehow possible (even without admin permissions), because I've seen something like that in Java - but I want to write it in ObjC

Sorry for my English - I hope you'll understand what I mean ;)

+6  A: 
NSPoint mouseLoc;
mouseLoc = [NSEvent mouseLocation]; //get current mouse position
NSLog(@"Mouse location: %f %f", mouseLoc.x, mouseLoc.y);

If you want it to continuously get the coordinates then make sure you have an NSTimer or something similar

Matt S.
wow, thanks! I didn't know it's that simple. I thought NSEvent would give me only in-window mouse position. I will accept your answer tommorow, after I'll test it works in the way I want to.
radex
+7  A: 

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.

Dave DeLong
I like this method :) It's much better then mine
Matt S.
It doesn't work for me :( I have no idea why, no output appeared.
radex
ok, never mind. Your solution is probably better, but it doesn't work. I'll just use [NSEvent mouseLocation] ;) Thanks anyway
radex
@radex it requires having an run loop in place.
Dave DeLong