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
Take a look at the _NET_ACTIVE_WINDOW value of the root window which is set by most modern window managers:
_NET_ACTIVE_WINDOW
xprop -root _NET_ACTIVE_WINDOW
This value can, of course, be obtained using Xlib library calls.