Skip to content

Instantly share code, notes, and snippets.

@elyase
Created September 21, 2014 10:11
Show Gist options
  • Save elyase/58d52de61f3f65b50921 to your computer and use it in GitHub Desktop.
Save elyase/58d52de61f3f65b50921 to your computer and use it in GitHub Desktop.
QuartztEvent Taps
import Quartz
from AppKit import NSKeyUp, NSSystemDefined, NSEvent
def keyboardTapCallback(proxy, type_, event, refcon):
# Convert the Quartz CGEvent into something more useful
if type_ < 0 or type_ > 0x7fffffff:
print "----- Timed out -----"
print NSEvent.eventWithCGEvent_(event)
return event
keyEvent = NSEvent.eventWithCGEvent_(event)
print keyEvent
# Set up a tap, with type of tap, location, options and event mask
eventMask = 239078654
tap = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap, # Session level is enough for our needs
Quartz.kCGHeadInsertEventTap, # Insert wherever, we do not filter
Quartz.kCGEventTapOptionListenOnly, # Listening is enough
eventMask, # NSSystemDefined for media keys
keyboardTapCallback,
None
)
runLoopSource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0)
Quartz.CFRunLoopAddSource(
Quartz.CFRunLoopGetCurrent(),
runLoopSource,
Quartz.kCFRunLoopDefaultMode
)
# Enable the tap
Quartz.CGEventTapEnable(tap, True)
# and run! This won't return until we exit or are terminated.
Quartz.CFRunLoopRun()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment