DDHotKey - Tracking without canceling event

219 views Asked by At

I'm using DDHotKey to track some system-wide keyboard shortcuts. When the event is fired, only my app gets it delivered. Is it possible to observe it without preventing the event from being delivered to its original target application?


Here's how this module registers the event handler:

InstallApplicationEventHandler(&dd_hotKeyHandler, 1, &eventSpec, NULL, NULL);

And the event handler itself:

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;
}

1

There are 1 answers

3
jscs On BEST ANSWER

No, the entire point of the hot key functionality is that the event is swallowed by the app that registers the key.

You want a global event monitor, which allows you to observe key events going anywhere else in the system, but not to affect them.

[NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyUpMask
                                       handler:^(NSEvent * event){
    // See if the key is the one you want and act on it.
}];