Getting “global” mouse position in Mac OS X

前端 未结 5 442
醉话见心
醉话见心 2020-12-24 02:41

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

5条回答
  •  伪装坚强ぢ
    2020-12-24 03:12

    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

提交回复
热议问题