Proper way to handle FormClosing event

Most common way to minimize an application is to override the FormClosing event by setting e.Handled = true; and then proceed to set form as hidden.

This creates a problem when the operating system want to close your application. The application simply refuses to close.

There are lots of solutions for this and in the past I've implemented an override to WndProc() and checked for WM_CLOSE message. This is not a very clean solution.

Today I found e.CloseReason and it's a beauty!

Check this out:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
 if (e.CloseReason == CloseReason.UserClosing)
 {
  // Minimize to system tray
  e.Cancel = true;
  this.Visible = false;
  this.notifyIcon1.Visible = true;
 }
}
The above solution will handle system shutdown etc etc.

It is also a very clean solution for MDI windows that you simply want to hide.

0 kommentarer:

Post a Comment