c++ - 来自 C++ 方法的消息传递 Objective-C 方法?

标签 c++ objective-c macos

我正在阅读这篇关于创建全局热键的文章。我已经成功完成了本教程,但现在我正在尝试向 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/

相关文章:

c++ - C++ 中的多态性 : Do I have to give child class functions the same arguments as the parents - how to overload

objective-c - Objective C 生成(空)WAV 文件

objective-c - Xcode 问题 : Quickly jump to a particular selector/class/symbol?

iphone - Core Animation (CABasicAnimation) 的不可预测行为

macos - InitWithCoder 从未调用过基于 Cocoa NSView 的类

c++ - 如何欺骗 QtCreator 关于宏定义的存在

c# - 可以使用 Boost 或 STL 显示自定义字符串的 C++ 断言?

macos - 如何在 macOS SwiftUI 中创建默认按钮?

mysql - 如何手动将.h文件导入系统库?

c++ - 有没有一种理想的方法可以避免这种使用 Naked New 的情况?