tags:

views:

403

answers:

2

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.

A: 

Use this XQueryTree to find the currently active, or top-most window.

Here is a function, when given a display, it will find the current window in focus:

static Window
GetCurrWindow(d)
Display *d;
{
Window foo;
Window win;
int bar;

    do{
    (void) XQueryPointer(d, DefaultRootWindow(d), &foo, &win,
        &bar, &bar, &bar, &bar, &bar);
    } while(win <= 0);


#ifdef VROOT
    {
    int n;
    Window *wins;
    XWindowAttributes xwa;

    (void) fputs("=xwa=", stdout);

    /* do{  */
        XQueryTree(d, win, &foo, &foo, &wins, &n);
    /* } while(wins <= 0); */
    bar=0;
    while(--n >= 0) {
        XGetWindowAttributes(d, wins[n], &xwa);
        if( (xwa.width * xwa.height) > bar) {
     win = wins[n];
     bar = xwa.width * xwa.height;
        }
        n--;
    }
    XFree(wins);
    }
#endif
    return(win);
}

http://tronche.com/gui/x/xlib/window-information/XQueryTree.html

I found the source:

http://examples.oreilly.com/networksa/tools/xsnoop.c

Good Luck

Aiden Bell
Aiden, thank you a lot. This code will help me. I've tried it and it reports which window is under the mouse pointer even if it this window doesn't have focus.I want to know the window that actually has focus. Is there a way my app can register itself as a listener to be informed about it? Or is there a function that can give this information without the need to use mouse position ?Thanks again.
Marcio Andrey Oliveira
@Marcio - It may well be worth checking out the xprop.c source file of the xprop package regarding what functions in libx11 it uses to obtain that information :)
Aiden Bell
I saw xprop.c ans xsnoop.c. I belive that I'll be able to adapt that code to use with XSetInputFocus and get the behaviour I want.Best Regards.
Marcio Andrey Oliveira
Cool, welcome to SO
Aiden Bell
A: 

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

xprop -root|grep ^_NET_ACTIVE_WINDOW

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

Marten
Marten, thanks for your reply.
Marcio Andrey Oliveira