0

I have started listening to global keyDown events. Is there a way to get information from which application that event came?

A handler receives NSNotification instance and NSEvent is part of it. Can I somehow extract that information from those objects?

Listening snippet:

[NSEvent addGlobalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *event){
    NSLog(@"global keyDown %@", event);
    [[NSNotificationCenter defaultCenter] postNotificationName:kKeyPressed
                                                        object:event];

}];

Observer:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyEventHandler:)
                                             name:kKeyPressed
                                           object:nil];

UPDATE

Global key downs are not send from any particular application. What I actually needed is to check for currently active application at event handler:

[[NSWorkspace sharedWorkspace] activeApplication]

This returns NSDictionary with information I needed.

lukaszb
  • 694
  • 1
  • 6
  • 15
  • This will _mostly_ work, but sometimes the active application will have switched by the time your handler runs. (For the most obvious and repeatable case, watch what you get for a cmd-tab event.) Hopefully that's good enough for you, but if it's not, I wanted you to know in advance rather than chasing it down as an unexplained bug 3 months after your software was released to the public (because we all know from experience how fun that can be). – abarnert Nov 08 '12 at 18:13
  • Thanks for comment, and yep, I have taken that under consideration already. For an app I'm working on it's totally enough for now. – lukaszb Nov 08 '12 at 21:47

1 Answers1

1

You're not posting a distributed notification, or using a distributed notification center. This means you know that the notification came from the current application.

Meanwhile, you're generating the notifications yourself, so if you did need to know the application, you could just add that in.

Finally, the events you're embedding are global key events, which do not have an associated application. Except in special cases, they're not generated by any application, they're generated by the user typing on the keyboard.

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • Thanks, marking as proper answer as it leads me to proper solution (see updated section in an answer). – lukaszb Nov 08 '12 at 11:07