title: Handling WM_ events in a windowless C# process
body: <p>I've been looking around for quite a while, and can't seem to find a good way to do this.</p>
  
  <p>Basically I have a C# process using WPF (which has no visible window), that I need to handle WM_ events in (such as <code>WM_CLOSE</code> or <code>WM_DESTROY</code> for example; so that I can elegantly shutdown when a user chooses to log off or restart their machine).</p>
  
  <p>There are a number of solutions I've seen out there that suggest using <code>System.Windows.InteropServices</code> to call <code>AddHook</code> and provide it a pointer to a function that then becomes the <code>WndProc</code>. The problem with this is, as far as I can tell, it depends on the window actually being visible (and in this case there is no window).</p>
  
  <p>Another way that's suggested but doesn't work is to override the <code>WndProc</code> method of a WinForm, but this process has no visible forms or windows.</p>
  
  <p>I've also found things referring to a Message-only Window. Some kind of invisible window that still receives WM_ events. From what I've seen, this is only available in a <code>Microsoft.WindowsCE.Forms</code> assembly. I added a reference to this assembly in my project and subclassed MessageWindow as indicated at: <a href="http://msdn.microsoft.com/en-us/library/microsoft.windowsce.forms.messagewindow.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/microsoft.windowsce.forms.messagewindow.aspx</a> but it still seems to not work. The breakpoints inside the WndProc are not being hit.</p>
  
  <p>Any clue?</p>