📜 ⬆️ ⬇️

Determining the reason for closing a Windows Forms application (.Net)

Prerequisites for writing an article


I was working on one application and my client wanted it to respond to system shutdown. I remembered that many applications performed some actions at closing, but I rarely met a program that would distinguish the way it was closed — by the user or the system. And I thought, why not show people that you can change something in the design of the application.

I saw several programs that subscribed to the FormClosing event and showed the MessageBox with a shutdown message, but when the application was closed by the system, it still showed this message and either data loss or suspension of system completion occurred.

So I decided to write an article about it.

main idea


FormClosingEventArgs is inherited from CancelEventArgs. FormClosingEventArgs has a CloseReason property that contains the reason for the shutdown. This can be used to determine the reason for closing.
')
Now there are two ways to get these arguments during shutdown.

1. You can override the OnClosing method of the Form class and cast CancelEventArgs to FormClosingEventArgs
protected override void OnClosing(CancelEventArgs e)
{
FormClosingEventArgs ce = e as FormClosingEventArgs;
if (ce != null )
{
//
}
base .OnClosing(e);
}
protected override void OnClosing(CancelEventArgs e)
{
FormClosingEventArgs ce = e as FormClosingEventArgs;
if (ce != null )
{
//
}
base .OnClosing(e);
}



2. You can subscribe to the FormClosing event:
private void SampleForm_FormClosing( object sender, FormClosingEventArgs e)
{
//
}
private void SampleForm_FormClosing( object sender, FormClosingEventArgs e)
{
//
}


Close processing


switch (ce.CloseReason)
{
case CloseReason.ApplicationExitCall:
// Exit Application
break ;
case CloseReason.FormOwnerClosing:
//
break ;
case CloseReason.MdiFormClosing:
// MDI
break ;
case CloseReason.None:
//
break ;
case CloseReason.TaskManagerClosing:
//
break ;
case CloseReason.UserClosing:
//
break ;
case CloseReason.WindowsShutDown:
// Windows
break ;
}
switch (ce.CloseReason)
{
case CloseReason.ApplicationExitCall:
// Exit Application
break ;
case CloseReason.FormOwnerClosing:
//
break ;
case CloseReason.MdiFormClosing:
// MDI
break ;
case CloseReason.None:
//
break ;
case CloseReason.TaskManagerClosing:
//
break ;
case CloseReason.UserClosing:
//
break ;
case CloseReason.WindowsShutDown:
// Windows
break ;
}




Fig. 1. Shut down Windows.


Fig. 2. Close the parent MDI window.


Fig. 3. Closing the program by the user.

Source: https://habr.com/ru/post/36963/


All Articles