

Introduction
This article is not an out of the box article. However I feel this may bring in some more ideas in the field of application development because knowledge makes you think beyond limitation.
Background
I was working with one application and my client wanted the application to be system shutdown aware. I remembered that lot many applications do some task based on closing of an application but rarely saw any application which differentiated user shutdown and system shutdown. I thought why not make people aware that there is something which may change in the application design.
I have seen a couple of applications which handle FormClosing
event and show MessageBox
of closing, but when system shutdown is requested, they still show the message and end up with either data loss or prevent system shutdown.
So I decided to put this in the form of an article.
Basic Idea
FormClosingEventArgs
is derived from CancelEventArgs
. FormClosingEventArgs
has a property (CloseReason
) which tells you the reason for closing. This may be used in identifying and handling the close reason.
Now you have two options to get this arguments during close.
You can override OnClosing
method declared in Form and cast CancelEventArgs e
to FormClosingEventArgs
:
protected override void OnClosing(CancelEventArgs e)
{
FormClosingEventArgs ce = e as FormClosingEventArgs;
if (ce != null)
{
}
base.OnClosing(e);
}
You can use event FormClosing
:
private void SampleForm_FormClosing(object sender, FormClosingEventArgs e)
{
}
Handle Close Scenario
switch (ce.CloseReason)
{
case CloseReason.ApplicationExitCall:
break;
case CloseReason.FormOwnerClosing:
break;
case CloseReason.MdiFormClosing:
break;
case CloseReason.None:
break;
case CloseReason.TaskManagerClosing:
break;
case CloseReason.UserClosing:
Handle User close
break;
case CloseReason.WindowsShutDown:
break;
}
Points of Interest
If you go through the MSDN documentation, you will find the following details of CloseReason
. The names itself are self explanatory:
ApplicationExitCall
- The Exit
method of the application class was invoked.FormOwnerClosing
- The owner form is closing.MdiFormClosing
- The parent form of this multiple document interface (MDI) form is closing.None
- The cause of the closure was not defined or could not be determined.TaskManagerClosing
- The Microsoft Windows Task Manager is closing the application.
UserClosing
- The user is closing the form through the user interface (UI), for example by clicking the Close button on the form window, selecting Close from the Window's control menu, or pressing ALT+F4. WindowsShutDown
- The operating system is closing all applications before shutting down.
History
- 28th January, 2008: Initial post