How to use CGEventCreateKeyboardEvent in Python on Mac?

巧了我就是萌 提交于 2019-12-19 09:49:06

问题


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 it at all on the internet, and plus I even have no idea what to import.

An example code would be nice, telling me what to import and what to put into python

Does anyone know the required code for the FN (FUNCTION KEY) in mac for CGEventCreateKeyboardEvent??


回答1:


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.



来源:https://stackoverflow.com/questions/21396985/how-to-use-cgeventcreatekeyboardevent-in-python-on-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!