WolfyD
WolfyD

Reputation: 873

c# Application exits when Main form closes

I'm writing a multi form application, and I'd like to be able to close Form1 with out the application closing.
Right now i'm using this.Hide to hide the form. Is there a way to set it so i can close any form, or the application should only exist when all the forms are closed?

I think i remember seeing something like that at one point, but that might not have been visual studio and c#.

Upvotes: 11

Views: 14470

Answers (4)

smbogan
smbogan

Reputation: 81

One strategy is to do something like the following:

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
    if (Application.OpenForms.Count == 0)
        Application.Exit();
}

If you place this on all of your forms, when the last one closes, the application will exit.

Upvotes: 6

Mauricio Gracia Gutierrez
Mauricio Gracia Gutierrez

Reputation: 10862

Based on your coments it's a single flow kind of application

I suggest that you implement the typical wizard interface on a single form with the BACK, NEXT, CANCEL buttons.

When the desired state has been reached, for example enough information has been gathered , the NEXT button is changed to a FINISH button.

Any time the user presses the CANCEL/FINISH button the window will close

And if you still want multiform you could still have it, in this you could have multiple flows at the same time and just finish or cancel the one that you want.

Upvotes: 0

dmay
dmay

Reputation: 1325

In your Program.cs file you have a line like Application.Run(new Form1()). Replace it with

var main_form = new Form1();
main_form.Show();
Application.Run();

Also you need to close application explicitly by call Application.Exit() where you want.

Upvotes: 21

Mauricio Gracia Gutierrez
Mauricio Gracia Gutierrez

Reputation: 10862

A multiform aplication should have a clear EXIT option (either by menu, toolbar), since you can not know that the user wants to close the program when the last window is closed (i supose that the user could go to the File/Open and open new windows)

An aplication that does something automatically that the user did not asked for can used frustration/confusion and spend time reopening the aplication.

Even the user can think that the application somehow crashed since he did not close it.

Upvotes: 1

Related Questions