开发者

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

I've successfully got a demo app intercepting keyboard events.开发者_如何学Go 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?


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.


Here how it goes:

int64_t processIdTarget = CGEventGetIntegerValueField(event, kCGEventTargetUnixProcessID);
int64_t processIdSource = CGEventGetIntegerValueField(event, kCGEventSourceUnixProcessID);

processIdSource shows you application sender and processIdTarget stands for receiver.

For example you can open virtual keyboard and send events with it. As virtual keyboard is process in user space you will get it's pid as processIdSource. But for most of cases you will get 0 as processIdSource.

After you got application's pid you can create NSRunningApplication instance and get bunch of information from it.


This shows process ID of the application that sent the event:

NSLog(@"Target PID:%lld",CGEventGetIntegerValueField(event, kCGEventTargetUnixProcessID));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜