3

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.

user310291
  • 36,946
  • 82
  • 271
  • 487
  • What's so "inelegant" about exiting the application when a form is closed if that's what you want to happen? – Ed S. Oct 31 '10 at 21:10
  • Inherit from `ApplicationContext` - see [here](http://stackoverflow.com/a/13406508/111794). – Zev Spitz Nov 16 '12 at 09:50

3 Answers3

4

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.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • I already mentionned Application.Exit is required. My problem is about how it is possible to hook the FormClosed Event globally so that I don't have maintenance hassle by doing the plumbing by hand each time I will add a new form class. – user310291 Nov 01 '10 at 04:22
  • I read your other thread and learned about ShutdownMode.AfterAllFormsClose that should solve my problem thanks. – user310291 Nov 01 '10 at 04:27
1

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.

Georgi
  • 395
  • 3
  • 4
1

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.

Jonathan
  • 1,487
  • 11
  • 12