Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top