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

后端 未结 1 2086
别跟我提以往
别跟我提以往 2021-02-15 04:08

I\'ve installed a keyboard hook:

CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {

Basically I

相关标签:
1条回答
  • 2021-02-15 05:00

    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
    
    0 讨论(0)
提交回复
热议问题