Search code examples
objective-ccocoamacosmacos-carbon

How can I tell which application a CGEventRef is coming from?


I've successfully got a demo app intercepting keyboard events. Here's the handler for them.

CGEventRef keyUpCallback (CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
    NSLog(@"KeyUp event tapped!");
    return;
}

I want to do different things depending on which application sent the event. How can I tell which application it is?


Solution

  • The application that is receiving keystrokes is presumably the active application, so you could handle the event differently depending on which application is active. You can use the activeapplication method from NSWorkspace to get the name of the active application.

    See also this thread about getting the active application.