Reputation: 38190
Let's say I launched multiples winforms from Program.cs with
Form1 form1 = new Form1();
form1.show();
Form2 form2 = new Form2();
form2.show();
Application.Run();
How do I quit application when all forms are closed by User ?
I can of course put Application.Exit() in FormClosed event but it's not very elegant I think. Are there other ways ?
Update: I mean it's not elegant to hard code each FormClosed each I have to add a new form. So is there a way I can HOOK ANY FormClosed event globally so that I can maintain the code in a central event handler without doing the PLUMBING BY HAND.
In some frameworks like Wordpress you can capture any event for any object globally I want the same kind of thing.
Upvotes: 3
Views: 793
Reputation: 941495
Application.Exit() is required in this case. Another approach is that you designate one of the forms as the "main window". And the app will terminate when it is closed:
Application.Run(form1);
The .NET framework also supports a "when last window closes" shutdown mode. Check my code in this thread for the required code.
Upvotes: 4
Reputation: 1507
You can maintain a List of the forms that are open, and, each time a form is closed have it delete itself from that list and then check if the list is empty. If the list is empty, end the application.
Upvotes: 1
Reputation: 395
Use Application.OpenForms to process all open forms and decide what to do with them. If you know which one should be saved - prompt the user, otherwise close it. And so on.
Upvotes: 1