Posted By

jimfred on 02/10/10


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


C# WinForm, cause 'close' ('X') to hide instead of disposing by handling the WM_CLOSE message in WndProc.

 / Published in: C#


Typical scenario: app pops up a dialog, user clicks 'X' and the dialog disposes. If the app attempts to access the dialog then runtime errors occur. This approach allows the app to retain access to the dialog to re-show the dialog.

An alternative would be for the app to check the disposed state of the dialog but this Close-->Hide approach is simpler and more transparent.

Source contains a simple WndProc that handles WM_CLOSE by calling Hide().

  1. protected override void WndProc(ref Message m)
  2. {
  3. const int WM_CLOSE = 0x0010;
  5. if (m.Msg == WM_CLOSE)
  6. {
  7. // I don't want 'X' to destroy the window - just hide it.
  8. // related: "Minimizing a window to the System Tray on a Close event" at
  9. //
  10. this.Hide();
  11. return;
  12. }
  14. base.WndProc(ref m);
  15. }

Report this snippet  

You need to login to post a comment.