Getting “global” mouse position in Mac OS X

走远了吗. 提交于 2019-12-02 18:41:07
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. 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.

If you're not in cocoa land and an event tap is not appropriate for the situation,

CGEventRef event = CGEventCreate(nil);
CGPoint loc = CGEventGetLocation(event);
CFRelease(event);

works.

Matt is correct, but in order to continuously get the coordinates, I believe the other option is to use event monitor provided by NSEvent. Try addGlobalMonitorForEventsMatchingMask:handler: and addLocalMonitorForEventsMatchingMask:handler:. Check NSEvent Class Reference for more detail.

For a continuous update on the global cursor position, here is what the code looks like (Swift 4.0.3):

override func viewDidLoad()
{
    super.viewDidLoad()

    NSEvent.addGlobalMonitorForEvents(matching: NSEvent.EventTypeMask.mouseMoved, handler: {(mouseEvent:NSEvent) in
        let position = mouseEvent.locationInWindow
    })
}

Note, the variable 'position' is an NSPoint object with x and y coordinates (among many other attributes). This will not return the coordinates if your application is in focus or when you are clicking and dragging. There are separate events for all of those: simply change the NSEvent.EventTypeMask.mouseMoved to a different EventTypeMask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!