How to tell the difference between a user-tapped keyboard event and a generated one?

风格不统一 提交于 2019-12-03 12:35:50

Take a look at the comments in CGEventSource.h. It's a little bit easier to put the information together than using the Event Services Reference. The long, but more correct, way around looks like creating an event source (which is subject to memory management rules; you need to CFRelease it if you're done using it before program termination):

myEventSource = CGEventSourceCreate(kCGEventSourceStatePrivate);

This will create your own private event source with a unique ID; you then indicate that events you create came from there:

CGEventRef myKeyboardEvent = CGEventCreateKeyboardEvent(myEventSource, 
                                                        keyCode, true);

When an event comes in, check to see if it's from yourself:

 if( (CGEventGetType(newEvent) == kCGEventKeyDown) &&
     (CGEventGetIntegerValueField(newEvent, kCGEventSourceStateID) == CGEventSourceGetSourceStateID(myEventSource) ) {

There's also a user data field for the source that lets you pass around an arbitrary 64 bits, should you need to.

The quick and dirty way would be to try picking an event field that isn't likely to be a meaningful value for a keyboard event, like kCGMouseEventPressure and turn it into a signature:

CGEventSetIntegerValueField(myKeyboardEvent, 
                            kCGMouseEventPressure, 
                            0xFEEDFACE);
// The field is an int_64 so you could make the sig longer
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!