Creating the main event loop (for hotkeys, etc.)

I am trying to write a standalone application for registering a global hotkey. Below is my code that I am compiling with gcc -framework Foundation -framework AppKit -framework Carbon -lstdc++ namsg.mm -o namsg.

I put

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

however, my hotkey (Command + 3) is not raised. This hotkey combination works because, because I was able to remove this code using javascript FFI, but now I'm trying to do it using Objective-C ++.

I also tried

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

Is there any other way to create a 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;
}
+1
source share

Source: https://habr.com/ru/post/1757376/


All Articles