tags:

views:

90

answers:

3

I have a simple window with 3 buttons and I am trying to add a system-wide hot key so i can "press" those buttons without having to switch to that app, press a button and then go back to what I was doing.

Something like Cmd+Shift+1 press button 1, Cmd+Shift+2 press button 2, etc.

Is there any way to achieve this in Cocoa (with Objective-C)? Thanks, code is appreciated since I am a total newbie on Cocoa.

+1  A: 

There is a library called PTHotKey that makes this fairly easy. You can google PTHotKey or just grab it from http://code.google.com/p/shortcutrecorder/source/browse/trunk/Demo/HotKey/?r=2

sbooth
thank you sbooth. question tho, when you say a library is it something I need to compile separatelly and then add to my app?
Jessica
+2  A: 

PTHotKey is old and busted (generates reams of warnings) on modern SDKs. Use SGHotKeysLib instead.

Both SGHotKeysLib and PTHotKey are reusable source code. You need only add the classes to your own project, then use them from your own classes.

Peter Hosey
great, thanks for the tip. Any chance you can post a little snippet? as I said, i'm only beginning with Cocoa
Jessica
+1  A: 

I also didn't like PTHotKey, so I ended up writing a new wrapper, available here:

http://github.com/davedelong/DDHotKey

edit

The 2 files you'd need are:

And you'd use it something like this:

- (IBAction) registerHotkey:(id)sender {
  DDHotKeyCenter * c = [[DDHotKeyCenter alloc] init];
  if (![c registerHotKeyWithKeyCode:kVK_ANSI_1 modifierFlags:(NSCommandKeyMask | NSShiftKeyMask) target:self action:@selector(hotkeyWithEvent:) object:nil]) {
    NSLog(@"unable to register hotkey");
  } else {
    NSLog(@"registered hotkey");
  }
  [c release];
}

- (void) hotkeyWithEvent:(NSEvent *)hkEvent {
  NSLog(@"Hotkey event: %@", hkEvent);
}
Dave DeLong
Thanks, sorry for the delay. It's been a busy week. This looks promising. Any way not to use the carbon framework?
Jessica
@Jessica yes, but not really. Yes if you're using 10.6 and you want to filter *every single key event* on the system looking for specific combinations to recognize. No if you want true hotkey behavior. I wouldn't worry about the Carbonness, though. This portion of Carbon was upgraded to be 64-bit compatible.
Dave DeLong
OK, let me try it. Two things: 1) do you have a direct link to a zip file (i don't use git and I can't find a download link on the page you posted). While the `how to use` is clear, I am a complete newbie. Do you have a small snippet that I can use as a guide for, let say, a hotkey cmd-shift-1?
Jessica
@Jessica edited answer
Dave DeLong
Jessica: Use the “Download Source” button on that page.
Peter Hosey
fantastic. thanks for the answer. it works really well.
Jessica
@Jessica glad to hear it. If you have any suggestions for how to improve the code, please let me know.
Dave DeLong