Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ways to quit application after launching multiple winforms?

Tags:

c#

winforms

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.

like image 286
user310291 Avatar asked Sep 12 '25 19:09

user310291


2 Answers

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.

like image 116
Hans Passant Avatar answered Sep 14 '25 09:09

Hans Passant


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.

like image 21
Georgi Avatar answered Sep 14 '25 08:09

Georgi