How to catch X11 Window Close Event

Working directly with X, Xlib, XUtils, and so on, is actually a lot more pleasant than I was lead to believe. However there are a couple of annoying bits. One of which, is handling events generated by XServer, and the WindowManager (WM) differently. Since the Chrome, or elements around your application, are supplied by the WM, you will need to listen to a message from it, and not a standard EventType from XServer.

Quick Code Snippet

Here are the magic lines to let the XServer know, you are interested in the Window Close Event.

(* this is in pascal *)
procedure ShowWindow();
var
  ...
  wmDelete : TAtom;
  ...

begin
  ...
  wmDelete := XInternAtom(display, 'WM_DELETE_WINDOW', True);
  XSetupWMProtocols(display, window, @wmDelete, 1);
  ...


  while True do
  begin
    XNextEvent(display, @e);
    ...
    
    (* In Event Loop *)
    if e._type = ClientMessage then
    begin
      
      (* Check that it is the message we want *)
      if e.xclient.data.l[0] = wmDelete then
      begin
        (* do your cleanup *)
        ...
        break;
      end;

    end; (* end if e._type  *)
  end; (* end while True *)
end; (* end procedure *)

It is super simple really. You just have to know that WM messages are all passed in as ClientMessage event types, and you need to explicitly create the hooks, to receive them.