问题
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