6

I found a couple of articles telling me how to make use of the WM_CLOSE message but never the less my application is the one who has to handle the WM_CLOSE message.

Is there a way to hook up the WM_CLOSE and handle it? Because the WM_CLOSE only closes the tray icon but does not terminate the process itself ...

Regards,

inva
  • 751
  • 2
  • 13
  • 28

2 Answers2

5

To do this you need to override the WndProc method on the Form which is the main tray icon and handle WM_CLOSE

private const int WM_CLOSE = 0x0010;

protected override void WndProc(ref Message m) {
  if (m.Msg == WM_CLOSE) {
    // Close everything
  }
  base.WndProc(ref m);
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 2
    Hey Jared,thanks a lot but this approach does not work for me because i use a more tray centric approach in writing a tray icon app. I'll use my own ApplicationContext and therefore don't got a "real" form. But the common ApplicationContext offers a Property named "MainForm" and all I needed to do was to handle the Closing event. – inva Mar 23 '12 at 07:25
  • @inva did you ever get this working? If my main form has `ShowInTaskBar = false` then the window will never receive the close message. – The Muffin Man Apr 17 '20 at 22:35
1

We can deal with WM_CLOSE message by adding a MessageFilter to Application:

private class CloseMessageFilter : IMessageFilter
{
    const int WM_CLOSE = 0x0010;
    
    public bool PreFilterMessage(ref Message m)
    {
        if (m.Msg == WM_CLOSE)
            Application.Exit();

        return false;
    }
}

static void Main()
{
    // ...
    Application.AddMessageFilter(new CloseMessageFilter());
    Application.Run();
}

Tested under .NET 6 only.