Is there some system level or accessibility API on macOS/Swift which would trigger callbacks whenever user interacts with mouse regardless of my app being in focus?
Ie something like a tray-app or background-service-app which would gather mouse events.
CodePudding user response:
What you are looking for is called NSEvent class method class func addGlobalMonitorForEvents(matching mask: NSEvent.EventTypeMask, handler block: @escaping (NSEvent) -> Void) -> Any?
. Note that it will only be called when your app IS NOT active:
NSEvent.addGlobalMonitorForEvents(matching: [.mouseMoved]) { event in
print("event:", event)
}
If you need to monitor the mouse events while your app IS active you need to monitor it locally using class func addLocalMonitorForEvents(matching mask: NSEvent.EventTypeMask, handler block: @escaping (NSEvent) -> NSEvent?) -> Any?
:
NSEvent.addLocalMonitorForEvents(matching: [.mouseMoved, .leftMouseDown, .mouseExited]) { event in
switch event.type {
case .mouseMoved: print("mouseMoved")
case .leftMouseDown: print("leftMouseDown")
default: print("other event")
}
return event
}