How to know which window has focus and how to change it?

x11
Plicatibu picture Plicatibu · Jun 18, 2009 · Viewed 15.6k times · Source

I would like to know how can I ask X11 which windows has focus. And if for any reason my own application (that may be visible or not) got the focus I want be able to let the former windows to get focus again.

For instance, my application is running with many others (e.g. firefox, gvim, nautilus,...)

Suppose that at first firefox has focus and that the user clicked on my app which now has the focus. I want that my application put focus on firefox again.

Does anyone knows how to achieve this? Books recommendations would be very nice.

Thanks a lot.

Answer

Marten picture Marten · Jun 19, 2009

Take a look at the _NET_ACTIVE_WINDOW value of the root window which is set by most modern window managers:

xprop -root _NET_ACTIVE_WINDOW

This value can, of course, be obtained using Xlib library calls.