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.
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.