Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To close C# Forms Application

I have 2 forms ...when i start the application..and use the close "X" from the title bar the entire application closes...now when i select an option from the 1st form in my case it is a button "ADD" as its a phonebook application..it goes to the 2nd form as i have used 1stform.hide() and 2ndform.show()...now when i do "X" from the title bar it doesnt shutdown completely as the 1stform is not closed....how to program it in such a way tht any stage the entire application should close

like image 822
Vinod K Avatar asked Feb 04 '11 12:02

Vinod K


2 Answers

Your first form is set as the startup form. That means whenever it gets closed, your entire application is closed. And conversely, your application does not close until it gets closed. So when you hide the startup form and show the second form, the user closing the second form does not trigger your application closing because they have only closed a secondary, non-modal dialog.

I recommend changing your design so that the startup form is also the main form of your application. No sense trying to work around built-in functionality that can actually be useful. You want the application to quit when the main form is closed, no matter what other child forms are opened.

But the quick-and-dirty solution in your case is to make a call to Application.Exit. That will close all of the currently open forms and quit your application immediately. As I said just above, I don't so much recommend this approach because having to call Application.Exit from every form's FormClosed event handler is a sign that something has gone seriously wrong in your design.

If the single startup form paradigm doesn't work out for you, you should look into taking matters into your own hands and customizing the Main method in your Program.cs source file. See the answers given to this related question for some ideas on how that might work for you.

like image 170
Cody Gray Avatar answered Nov 16 '22 00:11

Cody Gray


What you can do is to use the Form's FormClosing event, and add the following code:

Application.Exit();

This will stop the entire application, and close all windows. However, if a background thread is running, the process itself will survive. In this case you can use:

Environment.Exit();
like image 44
Øyvind Bråthen Avatar answered Nov 16 '22 00:11

Øyvind Bråthen