我在下面有这个代码,我在正常的Cocoa应用程序中实现了HotKeys。但是,当我尝试在命令行工具应用程序中实现相同的操作时,按下键时不会调用“OSStatus MyHotKeyHandler(EventHandlerCallRef nextHandler,EventRef theEvent,void * userData)”方法。我不明白我错过了什么。谁能发现错误?我哪里错了?提前感谢你。 。
#import "MainController.h"
@implementation MainController
@synthesize window = mWindow;
-(id)init
{
self = [super init];
if (self != nil) {
NSMutableDictionary *userDefaultsValuesDict = [NSMutableDictionary dictionary];
[userDefaultsValuesDict setObject:[NSNumber numberWithInt:123]forKey:@"hotkeyCodePlay"];
[userDefaultsValuesDict setObject:[NSNumber numberWithInt:cmdKey+optionKey]forKey:@"hotkeyModifiersPlay"];
[userDefaultsValuesDict setObject:[NSNumber numberWithInt:124]forKey:@"hotkeyCodeNext"];
[userDefaultsValuesDict setObject:[NSNumber numberWithInt:cmdKey+optionKey]forKey:@"hotkeyModifiersNext"];
[[NSUserDefaults standardUserDefaults] registerDefaults:userDefaultsValuesDict];
[[NSUserDefaults standardUserDefaults] synchronize];
}
return self;
}
-(void)awakeFromNib
{
//Register the Hotkeys
EventHotKeyRef gMyHotKeyRef;
EventHotKeyID gMyHotKeyID;
EventTypeSpec eventType;
eventType.eventClass=kEventClassKeyboard;
eventType.eventKind=kEventHotKeyPressed;
OSStatus status = InstallApplicationEventHandler(&MyHotKeyHandler,1,&eventType,(void*)self,NULL);
gMyHotKeyID.signature='htk1';
gMyHotKeyID.id=1;
if([[NSUserDefaults standardUserDefaults] integerForKey:@"hotkeyCodePlay"]!=-999) {
status = RegisterEventHotKey([[NSUserDefaults standardUserDefaults] integerForKey:@"hotkeyCodePlay"], [[NSUserDefaults standardUserDefaults] integerForKey:@"hotkeyModifiersPlay"], gMyHotKeyID, GetApplicationEventTarget(), 0,&gMyHotKeyRef);
}
gMyHotKeyID.signature='htk2';
gMyHotKeyID.id=2;
if([[NSUserDefaults standardUserDefaults] integerForKey:@"hotkeyCodeNext"]!=-999) {
status = RegisterEventHotKey([[NSUserDefaults standardUserDefaults] integerForKey:@"hotkeyCodeNext"], [[NSUserDefaults standardUserDefaults] integerForKey:@"hotkeyModifiersNext"], gMyHotKeyID, GetApplicationEventTarget(), 0,&gMyHotKeyRef);
}
}
OSStatus MyHotKeyHandler(EventHandlerCallRef nextHandler,EventRef theEvent, void *userData)
{
EventHotKeyID hkCom;
GetEventParameter(theEvent,kEventParamDirectObject,typeEventHotKeyID,NULL, sizeof(hkCom),NULL,&hkCom);
int l = hkCom.id;
MainController *selfObject = (MainController *)userData;
switch (l) {
case 1: //do something
NSLog (@"HOTKEY 1 PRESSED");
break;
case 2: //do something
[selfObject.window orderFrontRegardless];
NSLog (@"HOTKEY 2 PRESSED");
break;
}
return noErr;
}
@end