How can I detect how a windows form is being closed? For example, how do I find out whether the user has clicked on a button which closes the form or if the user clicks on the “X” in the upper-right? Thank you.
Update:
Forgot to mention that the button calls the Application.Exit() method.
As bashmohandes and Dmitriy Matveev already mentioned the solution should be the FormClosingEventArgs. But as Dmitriy also said, this wouldn’t make any difference between your button and the X in the right upper corner.
To distinguish between these two options, you can add a boolean property ExitButtonClicked to your form and set it to true in the button Click-Event right before you call Application.Exit().
Now you can ask this property within the FormClosing event and distinguish between those two options within the case UserClosing.
Example: