我正在阅读这篇关于创建全局热键的文章。我已经成功完成了本教程,但现在我正在尝试向 Objective-C 方法发送消息,但我被卡住了。有没有办法从 C++ 代码向 Objective-C 发送消息?
http://cocoasamurai.blogspot.com/2009/03/global-keyboard-shortcuts-with-carbon.html
这是我的代码所在的位置:
#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
最佳答案
如果您的 C++ 源文件的扩展名为 .mm
(而不是 .cpp
),那么它将被编译为 Objective-C++,您将能够发送就像使用标准的 .m
源文件一样向 Objective-C 对象发送消息。
关于c++ - 来自 C++ 方法的消息传递 Objective-C 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8549302/