public
Last active

Showing how to edit events from Quartz in Python

  • Download Gist
alter_keys.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#! /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();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.