Skip to content

Instantly share code, notes, and snippets.

@hiway
Created December 22, 2012 12:19
Show Gist options
  • Save hiway/4358680 to your computer and use it in GitHub Desktop.
Save hiway/4358680 to your computer and use it in GitHub Desktop.
Boilerplate/ minimum code needed to log keyboard and mouse activity on MacOSX. Logs only whether there was any activity or not, not the actual keys/ locations.
import time
from Cocoa import *
from Foundation import *
from PyObjCTools import AppHelper
last_timestamp = time.time()
class AppDelegate(NSObject):
def applicationDidFinishLaunching_(self, aNotification):
"""Sets events to be every keyboard click and left mouse click.
More information: http://l.hiwy.in/TJQ4qG
"""
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
NSKeyDownMask, handler
)
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
NSLeftMouseDownMask, handler
)
def handler(event):
"""Gets called every time there's an event/activity happening.
Sets last_timestamp to the time when an event occurs.
This can be used by a thread that's checking if there was any
activity in the last x minutes."""
last_timestamp = time.time()
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