tags:

views:

957

answers:

2

I have created an NSStatusBar cocoa application which sits in the system status bar.

I want to assign a hotkey so that when pressed it toggles my applications and show the menu.

Is this possible?, In my searching and experimenting I have found a few different ways of assigning global hot keys that can be pressed when your application is in the background but I can't find any way to problematically make the menu show.

Is this possible?, If anyone thinks a way of assigning a global hotkey is best please post it.

Thanks.


One of the hotkey tutorials I found was on http://dbachrach.com/blog/2005/11/program-global-hotkeys-in-cocoa-easily/ for anyone interested.

+4  A: 

If you're targeting 10.6+, there's some new API for NSEvent that can do global hotkeys. For more information, check out this awesome blog post: http://cocoakids.net/14-global-hotkeys-in-cocoa-on-snow-leopard

EDIT (a long time later)

Tooting my own horn a bit: I could never get things like PTHotKey and other libraries to work the way I was expecting, so I eventually gave up and wrote my own HotKey wrapper. It has a very simple API (you give it a key code, modifiers, a target, and an action), that even supports fun things like 10.6's blocks. You can download the source here: http://github.com/davedelong/DDHotKey

Dave DeLong
Thanks for the blog post, it works great but I think il use the other example so that it works in 10.5 aswell, Do you know if its possible to popup the apps menu via code?
Craig
@Craig you can do `[myStatusItem popUpStatusItemMenu:[myStatusItem menu]]`, although that won't highlight your statusitem (which is lame). The only other thing I'd suggest might be to fake a click over the statusitem.
Dave DeLong
Thank you very much
Craig
+5  A: 

There is an actual hotkey API, which still exists in Snow Leopard and is available in 64-bit. It's designed specifically for this purpose, unlike the NSEvent methods, which are essentially just a block-based wrapper around CGEventTaps.

The difference is that the NSEvent methods (or CGEventTaps directly) make you look at every event that comes in, whereas the hotkey API only calls your function when the user presses your hotkey.

Peter Hosey
Thank you, that works great, Do you know if its possible to popup the apps menu via code?
Craig
Craig: Yes. See Dave DeLong's comment on his answer.
Peter Hosey