Search code examples
cx11xlib

Closing application window with Xlib


I'm trying to close an application's window using Xlib from its ID. Having used wmctrl's source as a guide, below is a minimal C program that I think should achieve this, with the Window's ID being specified as argv[1].

#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>

int main (int argc, char *argv[]) {
    Display *disp;
    unsigned long wid;
    XEvent event;

    disp = XOpenDisplay(NULL);
    sscanf(argv[1], "0x%lx", &wid);

    long mask = SubstructureRedirectMask | SubstructureNotifyMask;

    event.xclient.type = ClientMessage;
    event.xclient.serial = 0;
    event.xclient.send_event = True;
    event.xclient.message_type = XInternAtom(disp, "_NET_CLOSE_WINDOW", False);
    event.xclient.window = (Window)wid;
    event.xclient.format = 32;
    event.xclient.data.l[0] = 0;
    event.xclient.data.l[1] = 0;
    event.xclient.data.l[2] = 0;
    event.xclient.data.l[3] = 0;
    event.xclient.data.l[4] = 0;

    XSendEvent(disp, DefaultRootWindow(disp), False, mask, &event);
}

I'm unsure as to what I'm not understanding/missing to achieve this.


Solution

  • Add this:

    XSync(disp, False);
    

    to the end of main. As written, your program exits before it has a chance to actually send a request to the server, because XLib buffers requests.