5

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?

Zarkonnen
  • 22,200
  • 14
  • 65
  • 81

1 Answers1

6

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.

Darren
  • 25,520
  • 5
  • 61
  • 71
  • The HotKey API sounds exactly like what I need, but I can't find any documentation on it at developer.apple.com. I guess I'd use LaunchServices to then open stuff based on triggered hotkeys? – Zarkonnen Aug 08 '12 at 09:30
  • 1
    Use DDHotKey, it's very simple to use. The keycode and modifierFlags parameters come from the NSEvent that's triggered by a key-down event. You can get those events by overriding -performKeyEquivalent: of a NSTextField. Also see Events.h, which defines most key codes. You can use [NSWorkspace openFile:] and [NSWorkspace openURL:] to simply launch an app, document, or URL. No need to use LaunchServices. – Darren Aug 08 '12 at 21:16
  • 1
    It needs to be a Cocoa app. A property in its Info.plist file determines whether the app is visible in the Dock or a hidden background app. – Darren Aug 10 '12 at 02:50