I am working in .NET4.5 Winforms C#.
My application is based on Model View Controller pattern. On the main form (view) I have a button Exit. If the user presses this button, a method is called on the controller that cleans up stuff and then calls Application.Exit(). This works fine.
I also would like to run this method when the user presses the default windows exit-cross in the top-right window. To do this I handle the FormClosing event. In this Event I call again the controller method which calls Application.Exit();
The problem now is that Application.Exit() also fires the FormClosing event. Which creates a double call. Of course I can make a flag and test for this, but I feel I am doing something wrong.
What is the correct way to close my winforms application and cleanup the required things. I don't want to cleanup in the formclosing event of the view, seems ugly.
The correct way of doing this is to include your cleanup code in a method that is being called in your FormClosing
event handler (nothing ugly in that, in my opinion). Calling Application.Exit
or closing the application the old-fashioned way then results in this event being generated. Which triggers the cleanup method.
private void Clicked(object sender, EventArgs e)
{
Application.Exit();
}
private void FormClosing(object sender, CancelEventArgs e)
{
Cleanup();
}
private void Cleanup()
{
// do cleanup here
}