Skip to content
pepijndevos edited this page Sep 13, 2010 · 7 revisions

Moving and clicking

This does not work reliable, but sometimes it does.

The idea behind this system is that you fetch a window, send events to it and sync it.

We need this stuff:

from Xlib.display import Display
from Xlib import X
from Xlib.protocol import event

Then we create a display and get the root element:

display = Display(":0")
root = display.screen().root

Before sending events we have to get the current window and compute the chords relative to that:

focus = display.get_input_focus().focus
rel = focus.translate_coords(root, x, y)

Now the event!
There is event documentation at Python-Xlib
This took me a lot of time to figure out, and it might be wrong, because it does not work on all systems.

mousePress = event.ButtonPress( # mouse event, needs a release to ;)
    time=X.CurrentTime,
    root=root,
    window=focus,
    same_screen=1,
    child=X.NONE,
    root_x=x,
    root_y=y,
    event_x=rel.x,
    event_y=rel.y,
    state=0,
    detail=1 # first button
    )

Now that we got an event, we got to send it to the event stream and call sync to make it actually work. <<< Important

focus.send_event(mousePress)
display.sync()

Getting information

This does seem to work.

Mouse position:

display.screen().root.query_pointer()._data

Returns a dict containing “root_x” and “root_y” amongst a few other things.

Screen size:

display.screen().width_in_pixels
display.screen().height_in_pixels
Clone this wiki locally