Question

I would like to know how to distinguish a form close between the user request and o.s. request (for example for a system shutdown). In the first case I want to ask exit confirmation, in the second I will exit without any other confirm.

Was it helpful?

Solution

The event args for the FormClosing event has a CloseReason property which exposes a CloseReason Enumerable value. This should tell you why the form is closing.

If the system is shutting down, it will contain the WindowsShutDown value.

If the user is closing the form by clicking the "x" button, then it will contain the UserClosing value.

Note that if you personally call the Form.Close() method from any method or event, it will likely have the None value, so if you are programatically closing your form via an event on an additional close button that you've added or after some action has been performed, you may have to handle that as well.

OTHER TIPS

Every form in its FormClosing event receives a FormClosingEventArgs where there are two properties named Cancel and CloseReason.

The first one allows to stop the closing of the form, the second one is an enum that defines a WindowsShutDown reason, so your code colud be

private void form_FormClosing(Object sender, FormClosingEventArgs e) 
{
   if(e.CloseReason != CloseReason.WindowsShutdown)
   {
      DialogResult d = MessageBox.Show("Closing app?", "MyApp", MessageBoxButton.YesNo );
      if(d == DialogResult.No)
         e.Cancel = true;
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top