How to use CGEventCreateKeyboardEvent in Python on Mac?

前端 未结 1 1919
渐次进展
渐次进展 2021-01-14 10:40

I have installed the pyobjc (with it Quartz), and I would like to know how one would properly create a keyboard event with CGEventCreateKeyboardEvent? Please? I can not find

相关标签:
1条回答
  • 2021-01-14 11:21
    evt = Quartz.CGEventCreateKeyboardEvent(None, vkey, True)
    

    That's all there is to it.

    And if you can find examples in C, like this one in the docs, it's trivial to map them to Python.

    C:

    CGEventRef event1, event2, event3, event4;
    event1 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)56, true);
    event2 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)6, true);
    event3 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)6, false);
    event4 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)56, false);
    

    Python:

    events = [Quartz.CGEventCreateKeyboardEvent(None, 56, True),
              Quartz.CGEventCreateKeyboardEvent(None, 6, True),
              Quartz.CGEventCreateKeyboardEvent(None, 6, False),
              Quartz.CGEventCreateKeyboardEvent(None, 56, False)]
    

    As for "what to import", if it's not obvious: import Quartz.

    If you want to map keys to key codes, the C docs can similarly be translated to Python, but this simple library wraps up the low-level functions and exposes them to Python.

    If you want a nice graphical way to find out what events are being sent through your system, try Event Taps Testbench. If you're on Maverick, you must read the note on Mavericks compatibility or it will not work. Anyway, run it, Add a tap on, e.g., Key Down, Key Up, and Flags Changed, click Current Event or Event History, and watch the key codes fly by.

    0 讨论(0)
提交回复
热议问题