Creating a main event loop (for hotkeys etc)

血红的双手。 提交于 2019-12-11 04:21:34

问题


I am trying to write a stand alone app to register a global hotkey. Below is my code which I compile with gcc -framework Foundation -framework AppKit -framework Carbon -lstdc++ namsg.mm -o namsg.

I have put in a

    do {
        event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantFuture] inMode: NSDefaultRunLoopMode dequeue:YES];
        if (event != nil) {
            [self handleEvent:event];
        }
    } while(true);

however my hotkey of (Command + 3) is not picked up. This hotkey combination does work because as I was able to pull off this code using javascript FFI, but now I am trying to do it with Objective-C++.

I also tried

[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

Is there another way I should create the main event loop?

#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#import <Carbon/Carbon.h>

void showAlert() {
    NSAlert *alert = [[[NSAlert alloc] init] autorelease];
    [alert setMessageText:@"Hi there."];
    [alert runModal];
}

OSStatus MyHotKeyHandler(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) {
    //Do something once the key is pressed
    showAlert();

    return noErr;
}

void registerHotkey() {
    EventHotKeyRef gMyHotKeyRef;
    EventHotKeyID gMyHotKeyID;
    EventTypeSpec eventType;
    eventType.eventClass=kEventClassKeyboard;
    eventType.eventKind=kEventHotKeyPressed;

    OSStatus installed = InstallApplicationEventHandler(&MyHotKeyHandler,1,&eventType,NULL,NULL);

    gMyHotKeyID.signature='htk1';
    gMyHotKeyID.id=1;

    OSStatus registered = RegisterEventHotKey(20, cmdKey, gMyHotKeyID, GetApplicationEventTarget(), 0, &gMyHotKeyRef);
}

int main(int argc, char * argv[]){

    registerHotkey();


    NSEvent* event;

    do {
        event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantFuture] inMode: NSDefaultRunLoopMode dequeue:YES];
        if (event != nil) {
            [self handleEvent:event];
        }
    } while(true);

    return 0;
}

来源:https://stackoverflow.com/questions/39704702/creating-a-main-event-loop-for-hotkeys-etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!