There is a lot of menu bar apps which display a panel with user interface when you click the menu bar icon. To make our life easier, these apps usually provide a global keyboard shortcut to access that panel without using your mouse.
Other apps just run in background and wait while you press a hotkey to perform some action. Evernote, Fantastical, Clocks, LittleSnapper, Things… all of these use global shortcuts to do their work. But how to implement this feature in you own Mac app?
In addition, we would need a control like
NSGlobalShortcutView to enter and display keyboard shortcuts with special characters for Command, Option and Shift, something like this.
From the links I just posted, you may find that adding support for global keyboard shortcuts is a non-trivial task. You have to dive into the component architecture, copy many sources or framework into your project, and finally add many lines of code into your app.
I always wanted to have something more lightweight and easy to use, something modern, something that will have simple APIs with blocks. And here we go, I would like to share a “framework” MASShortcut. I use it in my own apps CodeBox and Hunting, all code is compatible with latest OS X 10.7, with the Mac App Store and its sandboxed environment. So I hope you will find it useful :)
To use MASShortcut in a Cocoa app, git clone the repository from GitHub, link to the
Carbon.framework in Xcode and drag all Objective-C files into your project. Then insert a custom view of 19 pixels height into XIB and set its class to
MASShortcutView. Next, import
"MASShortcutView+UserDefaults.h" into the view controller and ask the shortcut view to read and store a hotkey in user preferences automatically. That's it for the UI part.
To listen for the global hotkey stored in user preferences, you have to import
"MASShortcut+UserDefaults.h" into the application delegate, for example. And then provide a block of code to execute when the user presses that global hotkey. This is really easy as you can see in README: