Skip to content

Instantly share code, notes, and snippets.

@tavisrudd
Forked from ljos/cocoa_keypress_monitor.py
Created July 6, 2012 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tavisrudd/3063165 to your computer and use it in GitHub Desktop.
Save tavisrudd/3063165 to your computer and use it in GitHub Desktop.
Showing how to listen to all keypresses in OS X through the Cocoa API using Python and PyObjC
# cocoa_keypress_monitor.py by Bjarte Johansen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
from AppKit import NSApplication, NSApp
from Foundation import NSObject, NSLog
from Cocoa import NSEvent, NSKeyDownMask
from PyObjCTools import AppHelper
class AppDelegate(NSObject):
def applicationDidFinishLaunching_(self, notification):
mask = NSKeyDownMask
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask, handler)
def handler(event):
try:
NSLog(u"%@", event)
except KeyboardInterrupt:
AppHelper.stopEventLoop()
def main():
app = NSApplication.sharedApplication()
delegate = AppDelegate.alloc().init()
NSApp().setDelegate_(delegate)
AppHelper.runEventLoop()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment