I’m reading this article about creating a global hotkey. I’ve gone through the tutorial successfully, but now I’m trying to message an Objective-C method, and I’m stuck. Is there a way to message Objective-C from C++ code?
http://cocoasamurai.blogspot.com/2009/03/global-keyboard-shortcuts-with-carbon.html
Here’s where my code is at:
#import "AppDelegate.h"
#import <Carbon/Carbon.h>
@implementation AppDelegate
@synthesize window = _window;
@synthesize statusItem;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
EventHotKeyRef myHotKeyRef;
EventHotKeyID myHotKeyID;
EventTypeSpec keyPressedEventType;
EventTypeSpec keyReleaseEventType;
keyPressedEventType.eventClass=kEventClassKeyboard;
keyPressedEventType.eventKind=kEventHotKeyPressed;
keyReleaseEventType.eventClass=kEventClassKeyboard;
keyReleaseEventType.eventKind=kEventHotKeyReleased;
InstallApplicationEventHandler(&keyPressedHandler, 1, &keyPressedEventType, NULL, NULL);
InstallApplicationEventHandler(&keyReleasedHandler, 1, &keyReleaseEventType, NULL, NULL);
myHotKeyID.signature='mhk1';
myHotKeyID.id=1;
RegisterEventHotKey(97, 0, myHotKeyID, GetApplicationEventTarget(), 0, &myHotKeyRef);
}
- (void)awakeFromNib
{
statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
[statusItem setMenu:statusMenu];
[statusItem setImage:[NSImage imageNamed:@"microphone_muted"]];
[statusItem setAlternateImage:[NSImage imageNamed:@"neg_microphone_muted"]];
[statusItem setHighlightMode:YES];
}
- (void) mute
{
[statusItem setImage:[NSImage imageNamed:@"microphone_muted"]];
[statusItem setAlternateImage:[NSImage imageNamed:@"neg_microphone_muted"]];
}
- (void) unmute
{
[statusItem setImage:[NSImage imageNamed:@"microphone"]];
[statusItem setAlternateImage:[NSImage imageNamed:@"neg_microphone"]];
}
OSStatus keyPressedHandler(EventHandlerCallRef nextHandler, EventRef anEvent, void *userData)
{
NSLog(@"Unmute mic");
return noErr;
}
OSStatus keyReleasedHandler(EventHandlerCallRef nextHandler, EventRef anEvent, void *userData)
{
NSLog(@"Mute mic");
return noErr;
}
@end
If your C++ source files have the extension
.mm(instead of.cpp), then it will be compiled as Objective-C++, and you will be able send messages to your Objective-C objects just as if you were using a standard.msource file.