Skip to content

Instantly share code, notes, and snippets.

@ljos
Last active August 12, 2024 17:34
Show Gist options
  • Save ljos/3019549 to your computer and use it in GitHub Desktop.
Save ljos/3019549 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
#!/usr/bin/env python
#
# cocoa_keypress_monitor.py
# Copyright © 2016 Bjarte Johansen <[email protected]>
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# “Software”), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Usage:
#
# Goto System Preferences > Security & Privacy > Accessibility and add
# Python to apps allowed to control your computer. If it is not in the
# list, the easiest is to run this file first and it should appear.
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()
@CrzPhil
Copy link

CrzPhil commented Aug 13, 2016

I get this error :
Traceback (most recent call last):
File "keylogger.py", line 1, in
from AppKit import NSApplication, NSApp
ImportError: No module named AppKit

And before you say somethin bout you gotta install appkit, I have I did all this pip install appkit thingy and it installed I think.
Please HELP!!!!

@skabbit
Copy link

skabbit commented Sep 3, 2016

Unable to stop the code control + C.
And can't get into handler. :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment