Skip to content

Instantly share code, notes, and snippets.

@cprovatas
Created January 6, 2018 21:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cprovatas/6acef442fc43123bcd5d5e937dc7951a to your computer and use it in GitHub Desktop.
Save cprovatas/6acef442fc43123bcd5d5e937dc7951a to your computer and use it in GitHub Desktop.
Monitor Mouse Event for any arbitrary application on macOS in Swift
let callback: CGEventTapCallBack = { (tapProxy, eventType, event, refcon) -> Unmanaged<CGEvent>? in
debugPrint("we are monitoring the mouse event here")
return nil
}
let eventMask = (1 << CGEventType.leftMouseDown.rawValue) | (1 << CGEventType.leftMouseUp.rawValue)
let machPort = CGEvent.tapCreateForPid(pid: 40529, place: .tailAppendEventTap, options: .defaultTap, eventsOfInterest: CGEventMask(eventMask), callback: callback, userInfo: nil)!
let runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, machPort, 0)
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes)
CGEvent.tapEnable(tap: machPort, enable: true)
CFRunLoopRun()
@jaunruh
Copy link

jaunruh commented Feb 6, 2020

Is there any way to use this code to prevent events from being forwarded to the application? I am trying to prevent my cursor from being replaced whenever I hover over the dock. Even tho I return nil within the callback, the dock still receives the events.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment