UPDATE: It now also has the code to watch for the active window’s title changing without the window having to lose and regain focus.
I needed to explain to someone the proper way to watch a Linux desktop for changes to the active window (ie. When the user focuses a new window) and, since I had a surprising amount of trouble finding a reliable way to do this, I thought I’d blog about it.
The first thing you’re likely to see when you go looking for this is people polling commands like
xprop to get that information. I think everyone knows this is a method of last resort. All the people doing it seem to.
Option two, once you compose the right search queries, is to watch
FocusOut and possibly
FocusIn events across your whole desktop. Some people seem to get that working but, unfortunately, it was very erratic on my KDE 4.x desktop.
Finally, the solution that’s both simple (by X11 standards) and seems to work reliably for me. I’d like to thank @alanc on StackOverflow for drawing my attention to this: You can opt into property-change notifications on the root window and watch
_NET_ACTIVE_WINDOW. (Which is a standard property maintained by any modern window manager)
You will still want to do your own change checking, though. Watching the property is good for minimizing resource consumption, but I did receive duplicate events.