Xlib: watching key presses without trapping them

Raffaele Ricciardi rfflrccrd at gmail.com
Sat Aug 11 05:53:37 EDT 2012


Hello there,

I'm writing a X Windows program to perform some actions when modifier 
keys have
been released.  After looking into the Pykeylogger project
(pykeylogger.sourceforge.net), I've gone as far as detecting all events 
related
to modifiers, but then such events get trapped by the program and do not 
reach
other applications.

I'm using Python 2.7.3.  Thanks for your help.

Here it is the program:

#! /usr/bin/env python

from Xlib.display import Display
from Xlib import X

Control_R  = 64  # Keycode for right Control.
Control_L  = 108 # Keycode for left Control.
# Keycodes we are listening for.  I've left out Right Control
# to be able to stop the program.
keycodes = [Control_L]

# Handle X events.
def handle_event(event):
     # Let us know whether this event is about a Key Release of
     # one of the keys in which we are interested.
     if event.type == X.KeyRelease:
         keycode = event.detail
         if keycode in keycodes:
             print "KeyRelease"

# Objects needed to call Xlib.
display = Display()
root = display.screen().root

# Tell the X server we want to catch KeyRelease events.
root.change_attributes(event_mask = X.KeyReleaseMask)

# Grab those keys.
for keycode in keycodes:
     root.grab_key(keycode, X.AnyModifier, 1, X.GrabModeAsync, 
X.GrabModeAsync)

# Event loop.
while 1:
     event = root.display.next_event()
     handle_event(event)

# End of program.



More information about the Python-list mailing list