alecail
alecail

Reputation: 4052

How to send keyboard events to my application when it is not the front application?

I would like my application to receive a notification when a certain keyboard event happens (for example left alt-key depressed twice in less than 0.5 second). The application is not supposed to be the front application. How can I do this ?

Upvotes: 1

Views: 290

Answers (1)

Smilin Brian
Smilin Brian

Reputation: 990

You'll need to install an event tap for modifier key changes.

This ought to get you started:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    CFMachPortRef eventTap;
    CGEventMask eventMask;
    CFRunLoopSourceRef runLoopSource;

    eventMask = CGEventMaskBit(kCGEventFlagsChanged);

    eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0,
                                eventMask, KeyHandler, NULL);
    if (!eventTap) {
        NSLog(@"failed to create event tap");
        exit(1);
    }

    runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);    
    CGEventTapEnable(eventTap, true);
}

static CGEventFlags previousFlags = 0;

CGEventRef KeyHandler(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
    if (type == kCGEventFlagsChanged) {
        CGEventFlags curAltkey = CGEventGetFlags(event)&kCGEventFlagMaskAlternate;
        if (curAltkey != previousFlags)
            NSLog(@"alt key changed");
    }

    return event;
}

Upvotes: 2

Related Questions