Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "global" mouse position in Mac OS X

Tags:

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 ;)

like image 698
radex Avatar asked Feb 14 '10 19:02

radex


People also ask

How do I find my cursor coordinates on a Mac?

Answer: A: It does not use an AppleScript, Shell Script or anything else, but if you are just looking to get the coordinates of the mouse on the screen, +command, shift 4+ will give you the coordinates. Then press escape when you have them.

How do I get my mouse cursor position?

Once you're in Mouse settings, select Additional mouse options from the links on the right side of the page. In Mouse Properties, on the Pointer Options tab, at the bottom, select Show location of pointer when I press the CTRL key, and then select OK. To see it in action, press CTRL.


2 Answers

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

like image 78
Matt S. Avatar answered Sep 26 '22 15:09

Matt S.


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.

like image 29
Dave DeLong Avatar answered Sep 24 '22 15:09

Dave DeLong