#! /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();