Catch the right closing event
Whenever a Windows Form is closed, you can catch this event by overriding the OnClosing() method. In this method you have the option to do some cleanup before it closes. You can also prevent the Form from closing by cancelling the closing event. That means that you can turn off the ability to exit a Windows Forms application very easily and for some applications that’s just what you want. You probable just want to hide it and let it run in the background.
The only problem is that if the application cannot be closed, then you cannot turn of Windows because it keeps trying to close the enclosable application. That was a problem for the Site Monitor application, so I started reading the MSDN documentation for a way to fix this issue.
What I found was a new method called OnFormClosing() that is new to the .NET Framework 2.0. I also found that OnClosing() has been deprecated but the Intellisense in Visual Studio didn’t show that. The OnFormClosing() tells you whether it was the user who closed it or if Windows are shutting down or some other reason.
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (e.CloseReason
== CloseReason.UserClosing)
{
e.Cancel
= true;
DoSomething();
}
}
>
So remember to catch the right event and make sure Windows is able to shut down properly.