T.L
T.L

Reputation: 717

How to get the active window using X11/Xlib c api?

I cannot find in the The Xlib Manual how to get the active window?

Is it the "focus window" that I obtain using XGetInputFocus?

Or should I query the root window property _NET_ACTIVE_WINDOW? According to Wikipedia, this property "gives the currently active window".

So I wanted to use the function XGetWindowProperty to get the property _NET_ACTIVE_WINDOW, but I have no idea what value I should give to parameters that I do not understand like long_offset, long_length, delete, req_type...

I am using Linux (Ubuntu).

Upvotes: 1

Views: 1779

Answers (1)

XGetWindowProperty(
    Display *display; //display object, e.g. via XopenDisplay(NULL)
    Window w;         //root window, e.g. via DefaultRootWindow(display)
    Atom property;    //the requested property, here: _NET_ACTIVE_WINDOW
    long long_offset; //offset into returned data (32 bit quantity)
    long long_length; //length of data to return (32 bit quantity)
    Bool delete;      //False (as long you don't want to delete the property)
    Atom req_type;    //what type we expect, here we expect a window: XA_WINDOW
    Atom *actual_type_return; //an Atom or any XA_* of what is actually returned
    int *actual_format_return; //depends, read the spec of what will be returned, here: 32
    unsigned long *nitems_return; //how many items are returned, we expect 1
    unsigned long *bytes_after_return; //important on partial read
    unsigned char **prop_return; //pointer to the items
);

Example:

//open default display
Display *display = XOpenDisplay(NULL);
//get default root window of display
Window root = DefaultRootWindow(display);
//get the atom of the property
Atom property = XInternAtom(display, "_NET_ACTIVE_WINDOW", False); 

//return values
Atom type_return;
int format_return;
unsigned long nitems_return;
unsigned long bytes_left;
unsigned char *data;

XGetWindowProperty(
    display,
    root,
    property,
    0,              //no offset
    1,              //one Window
    False,
    XA_WINDOW,
    &type_return,   //should be XA_WINDOW
    &format_return, //should be 32
    &nitems_return, //should be 1 (zero if there is no such window)
    &bytes_left,    //should be 0 (i'm not sure but should be atomic read)
    &data           //should be non-null
);

//(return_value == Success) && nitems_return
Window win = ((Window*) data)[0];
XFree(data);

Useful links:

Upvotes: 3

Related Questions