Search code examples
macoseventskeyboard

Listening for keyboard presses in OS X


I'm trying to write a simple launcher app for OS X. This means writing a background process that can listen for keys being pressed. How is this done in OS X? Can I install a listener somewhere, or can I poll the current state of the keyboard?


Solution

  • If you want to create a global keyboard shortcut for your app, use the HotKey API. (Although the HotKey API is an old Carbon/CoreServices API, it is available to 64-bit Cocoa apps and is still fully supported and not deprecated in 10.8 Mountain Lion.)

    DDHotKey is a nice Cocoa wrapper for the Carbon HotKey API.

    To listen to all keystrokes from all apps, use +[NSEvent addGlobalMonitorForEventsMatchingMask:handler:]; however, that is not the correct way to implement a launcher app.