You should take a look at the NSEvent mouseLocation method
edit / update: Xcode 8.2.1 • Swift 3.0.2
If you want to track events in any window when your application is active, you can add LocalMonitorForEvents corresponding to the mouseMoved mask, and if it is not active, GlobalMonitorForEvents:
class ViewController: NSViewController { lazy var window: NSWindow = self.view.window! var mouseLocation: NSPoint { return NSEvent.mouseLocation } var location: NSPoint { return window.mouseLocationOutsideOfEventStream } override func viewDidLoad() { super.viewDidLoad() NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved]) { print("mouseLocation:", String(format: "%.1f, %.1f", self.mouseLocation.x, self.mouseLocation.y)) print("windowLocation:", String(format: "%.1f, %.1f", self.location.x, self.location.y)) return $0 } NSEvent.addGlobalMonitorForEvents(matching: [.mouseMoved]) { _ in self.mouseLocation = NSEvent.mouseLocation() print(String(format: "%.0f, %.0f", self.mouseLocation.x, self.mouseLocation.y)) } } }
note: you need to set your acceptptsMouseMovedEvents window property to true
window.acceptsMouseMovedEvents = true
Leo dabus
source share