CGEventPost - possible bug when simulating keyboard events?

前端 未结 6 1297
挽巷
挽巷 2020-12-01 05:04

I have a very simple chunk of code that is designed to simulate keyboard events. The simple example below should type \"Cz\" - the shift key goes down, the c key goes down,

6条回答
  •  盖世英雄少女心
    2020-12-01 05:20

    I have found a reliable way to post modified keyboard events - it does not follow the example in Apple's documentation (which doesn't work) but seems to make sense, and most importantly, WORKS.

    Rather than sending 'shift key down' and 'shift key up' messages (as instructed in the docs), you need to set a modifier flag on the keypress. Here's how to output an uppercase Z.

    CGEventRef event1, event2;
    event1 = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)6, true);//'z' keydown event
    CGEventSetFlags(event1, kCGEventFlagMaskShift);//set shift key down for above event
    CGEventPost(kCGSessionEventTap, event1);//post event
    

    I'm then releasing the 'z' key for completeness (also setting the shift-flag on, though not sure if this is correct).

    event2 = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)6, false);
    CGEventSetFlags(event2, kCGEventFlagMaskShift);
    CGEventPost(kCGSessionEventTap, event2);
    

    Finally (and bizarrely) you DO need to send the 'key up' event for the shift key:

      e5 = CGEventCreateKeyboardEvent(NULL, (CGKeyCode)56, false);
    CGEventPost(kCGSessionEventTap, e5);
    

    Don't forget to release your events once you're done with them.

    I hope this is useful to someone - it took me a long time to get this to work.

提交回复
热议问题