我使用DDHotKey来跟踪一些系统范围的键盘快捷键。当事件被触发时,只有我的应用被交付。是否有可能在不阻止事件传递到其原始目标应用程序的情况下观察它?
这个模块是如何注册事件处理程序的:
InstallApplicationEventHandler(&dd_hotKeyHandler, 1, &eventSpec, NULL, NULL);
和事件处理程序本身:
OSStatus dd_hotKeyHandler(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) {
@autoreleasepool {
EventHotKeyID hotKeyID;
GetEventParameter(theEvent, kEventParamDirectObject, typeEventHotKeyID, NULL, sizeof(hotKeyID),NULL,&hotKeyID);
UInt32 keyID = hotKeyID.id;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"hotKeyID = %u", keyID];
NSSet *matchingHotKeys = [[DDHotKeyCenter sharedHotKeyCenter] hotKeysMatchingPredicate:predicate];
if ([matchingHotKeys count] > 1) { NSLog(@"ERROR!"); }
DDHotKey *matchingHotKey = [matchingHotKeys anyObject];
NSEvent *event = [NSEvent eventWithEventRef:theEvent];
NSEvent *keyEvent = [NSEvent keyEventWithType:NSKeyUp
location:[event locationInWindow]
modifierFlags:[event modifierFlags]
timestamp:[event timestamp]
windowNumber:-1
context:nil
characters:@""
charactersIgnoringModifiers:@""
isARepeat:NO
keyCode:[matchingHotKey keyCode]];
[matchingHotKey invokeWithEvent:keyEvent];
}
return noErr;
}
不,热键功能的全部意义在于该事件被注册该键的应用程序所吞噬。
您需要一个全局事件监视器,它允许您观察系统中其他地方发生的关键事件,但不影响它们。
[NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyUpMask
handler:^(NSEvent * event){
// See if the key is the one you want and act on it.
}];