我正在尝试编写一个独立的应用程序来注册全局热键。下面是我用gcc -framework Foundation -framework AppKit -framework Carbon -lstdc++ namsg.mm -o namsg
编译的代码。
我已经加入了
do {
event = [NSApp nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantFuture] inMode: NSDefaultRunLoopMode dequeue:YES];
if (event != nil) {
[self handleEvent:event];
}
} while(true);
然而我的(Command + 3)热键没有被拿起。这个热键组合确实有效,因为我能够使用javascript FFI来提取这些代码,但现在我正在尝试使用Objective-C ++。
我也试过
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
我是否应该采用另一种方式创建主事件循环?
#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;
}