title: How to detect window creation and closing?
body: <p>I can't find a way to add a callback for when a window is closed - and also not a reliable way to react to newly created windows. </p>
  
  <p>My application creates a few processes using <code>subprocess.Popen</code>. Each process has a visible window. The processes share some events with <em>pyHook</em>, using <code>PumpMessages</code> for this.</p>
  
  <p>I use this method to get a handle to each window: <a href="http://timgolden.me.uk/python/win32_how_do_i/find-the-window-for-my-subprocess.html" rel="nofollow">Tim Golden: Find the window for my subprocess</a><br>
  This method first sleeps a bit to wait for the windows' creation, then uses <code>EnumWindows</code> and compares the pid. Ok, this method sometimes works, if given enough time, and sometimes stays idle way to long. Obviously waiting for a notification that a new window was created would be better.</p>
  
  <p>Same goes for closing a window. I guess I can check a handle with <code>IsWindow</code> in the pyHook events, but that doesn't seem right. I haven't found any python examples for this, the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms632598%28v=VS.85%29.aspx#destroying_win" rel="nofollow">msdn examples</a> say <code>WM_CLOSE</code> will be send, but I can't get it to listen for any messages (nothing ever happens, I only see my pyHook events). I'm not even sure if I'm using <code>HookMessage</code> correctly here:</p>
  
  <pre><code>def close_window(hwnd, msg):
      print "closed " + str(hwnd)
  
  window = win32ui.CreateWindowFromHandle(hwnd)
  # WM_CLOSE 0x0010
  window.HookMessage(close_window,0x0010)
  </code></pre>
  
  <p>Is there a way to add a callback that gets executed when a process creates a window?<br>
  How can I get a callback to be executed when a window is closed? </p>