Getting mouse coordinates in Swift

Swift is new here.

I am having problems with a task that should be trivial. All I want to do is get the x, y coordinates of the mouse cursor on request . I would rather not wait for the mouse to move before I can grab the pointers.

Would thank for any help!

+11
swift macos
source share
1 answer

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 
+21
source share

All Articles