Search code examples
pythonuser-interfacewnck

Determining active window / application with wnck (python) fails


in my python-script i have to determine the actual active window / application to react on remote-events (lirc) application dependent. So i tried to relaize it like described here. But the test-code

import wnck, time

run = True
while run:
    try:
        time.sleep(1)
        screen = wnck.screen_get_default()
        #screen.force_update()
        print screen.get_active_window().get_name()
        print screen.get_previously_active_window()
    except KeyboardInterrupt:
        run = False

results in this output

.lirc : python — Konsole
None
.lirc : python — Konsole
None
.lirc : python — Konsole
None
.lirc : python — Konsole
None
.lirc : python — Konsole
None

even if i switch to another window. Therefore i repeated the execution and delayed it with time.sleep(1). Executed by a remote-event (lirc) the result is the same. Only within the python shell it seams to work (there screen.get_previously_active_window() has a / the right result). The script has been executed within a terminal window (konsole) of Kubuntu 16.04. I've tested to insert screen.force_update(), but without success.

What i'm doing wrong?

Thanks


Solution

  • I've solved it now with the Xlib. This way it works independent. Here's an example-code:

    import Xlib
    import Xlib.display
    import time
    
    run = True
    while run:
        try:
            time.sleep(1)
    
            display = Xlib.display.Display()
            root = display.screen().root
            windowID = root.get_full_property(display.intern_atom('_NET_ACTIVE_WINDOW'), Xlib.X.AnyPropertyType).value[0]
            window = display.create_resource_object('window', windowID)
    
            print window.get_wm_name()
            print window.get_full_property(display.intern_atom('_NET_WM_PID'), Xlib.X.AnyPropertyType).value[0]
            print window.get_full_property(display.intern_atom('_NET_WM_NAME'), Xlib.X.AnyPropertyType).value[0]
            print window.get_full_property(display.intern_atom('_NET_WM_VISIBLE_NAME'), Xlib.X.AnyPropertyType)
            print window.get_wm_class()
        except KeyboardInterrupt:
            run = False
    

    There are shown some possible informations about the window. In my final script I'm using window.get_wm_class().