You want the FocusOut
X event.
The X server can report FocusIn or FocusOut events to clients wanting
information about when the input focus changes. The keyboard is always
attached to some window (typically, the root window or a top-level
window), which is called the focus window. The focus window and the
position of the pointer determine the window that receives keyboard
input. Clients may need to know when the input focus changes to
control highlighting of areas on the screen.
To receive FocusIn or FocusOut events, set the FocusChangeMask bit in
the event-mask attribute of the window.