Skip to content

Instantly share code, notes, and snippets.

@ljos
Last active September 5, 2018 01:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ljos/4135908 to your computer and use it in GitHub Desktop.
Save ljos/4135908 to your computer and use it in GitHub Desktop.
Showing how to edit events from Quartz in Python
#! /usr/bin/python2.6
# I COULD ONLY GET IT TO RUN IN PYTHON2.6
# Running it in python2.7, installed from homebrew results in a segfault.
# I haven't been able to investigate why.
# Code translated from http://osxbook.com/book/bonus/chapter2/alterkeys/
# License: http://ljos.mit-license.org/
from Quartz import (
CGEventGetIntegerValueField, CGEventSetIntegerValueField,
kCGKeyboardEventKeycode,
kCGEventKeyDown, kCGEventKeyUp,
CGEventTapCreate,
kCGSessionEventTap, kCGHeadInsertEventTap,
CFMachPortCreateRunLoopSource,
kCFAllocatorDefault,
CFRunLoopGetCurrent,
kCFRunLoopCommonModes,
CFRunLoopAddSource,
CGEventTapEnable,
CFRunLoopRun)
# This callback will be invoked every a key is pressed.
def eventCallBack(proxy, etype, event, refcon):
# The incoming keycode.
keycode = CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode)
#Swap 'a' and 'z'
if keycode == 0:
keycode = 6
elif keycode == 6:
keycode = 0
CGEventSetIntegerValueField(event, kCGKeyboardEventKeycode, keycode)
return event
if __name__ == '__main__':
eventMask = (1 << kCGEventKeyDown) | (1 << kCGEventKeyUp)
eventTap = CGEventTapCreate(kCGSessionEventTap,
kCGHeadInsertEventTap,
0,
eventMask,
eventCallBack,
None);
if not eventTap:
print "failed to create event tap\n"
else:
runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault,
eventTap,
0)
CFRunLoopAddSource(CFRunLoopGetCurrent(),
runLoopSource,
kCFRunLoopCommonModes);
CGEventTapEnable(eventTap, True);
CFRunLoopRun();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment