How can I use python xlib to generate a single keypress? -


i want make simple python 3 script generate single keypress (f15). don't want use bunch of libraries need 1 key pressed , don't need support whole keyboard. know need use keypress , keyrelease in order generate keyboard event. i'm not sure start , documentation little confusing.

http://tronche.com/gui/x/xlib/events/keyboard-pointer/keyboard-pointer.html http://python-xlib.sourceforge.net/?page=documentation

i'll use ctypes show how work, porting python-xlib should straightforward. lets start loading library:

import ctypes x11 = ctypes.cdll("libx11.so") 

and defining structures needed:

class display(ctypes.structure):     """ opaque struct """  class xkeyevent(ctypes.structure):     _fields_ = [             ('type', ctypes.c_int),             ('serial', ctypes.c_ulong),             ('send_event', ctypes.c_int),             ('display', ctypes.pointer(display)),             ('window', ctypes.c_ulong),             ('root', ctypes.c_ulong),             ('subwindow', ctypes.c_ulong),             ('time', ctypes.c_ulong),             ('x', ctypes.c_int),             ('y', ctypes.c_int),             ('x_root', ctypes.c_int),             ('y_root', ctypes.c_int),             ('state', ctypes.c_uint),             ('keycode', ctypes.c_uint),             ('same_screen', ctypes.c_int),         ]  class xevent(ctypes.union):     _fields_ = [             ('type', ctypes.c_int),             ('xkey', xkeyevent),             ('pad', ctypes.c_long*24),         ]  x11.xopendisplay.restype = ctypes.pointer(display) 

now need send event root window:

display = x11.xopendisplay(none) key = xevent(type=2).xkey #keypress key.keycode = x11.xkeysymtokeycode(display, 0xffcc) #f15 key.window = key.root = x11.xdefaultrootwindow(display) x11.xsendevent(display, key.window, true, 1, ctypes.byref(key)) x11.xclosedisplay(display) 

this minimal example worked me (just using f2 instead). same can done send keyrelease event. if special window targeted, key.window should set appropriately.

i'm not sure, if it's necessary use xevent union, since it'd worked xkeyevent alone me, it's better safe.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

node.js - How to abort query on demand using Neo4j drivers -