I can determine the current mouse pointer position with:
from Xlib.display import Display
display = Display()
qp = display.screen().root.query_pointer()
print(qp.root_x, qp.root_y)
How do I get the current mouse button states like left/right button pressed/released via Xlib, too? (Or if this is not possible - why not?)
Your X window must support XInput extension. Real X works but getting to mouse button doesn't work if the X server doesn't support the extension like VNC server.
If the X server supports it, then you can get to the mouse state as follows:
from Xlib.display import Display
from Xlib.ext import xinput
display = Display()
import time
while True:
buttons = []
for device_info in display.xinput_query_device(xinput.AllDevices).devices:
if not device_info.enabled:
continue
if xinput.ButtonClass not in [ device_class.type for device_class in device_info.classes ]:
continue
buttons.append(device_info)
for button in buttons:
for device_class in button.classes:
if xinput.ButtonClass == device_class.type:
if device_class.state[0]:
print('Device {name} - Primary button down'.format(name=button.name))
time.sleep(1)
I'm not 100% sure as the docs are not found anywhere, but I'm pretty sure device_class.state[0] is primary (left button), 1 is middle, and 2 is right button.
You can probably find out the button number assignment spec here
EDIT:
Why there are two for loops - First I wrote the "buttons" part outside of forever loop. But, "hey, you can plug in mouse any time."
You'll find that, there are many devices including "virtual" ones. On laptop, touchpad does work as button too so in your app, if you want to know the real mouse's buttons, you may have to pick a device from name. Again, there is no good docs so you probably have to decipher the device class object. You can find the xinput as /usr/lib/python3/dist-packages/Xlib/ext/xinput.py. (Adjust it accordingly if you are using Python2.) Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With