Mohammad Areeb Siddiqui
Mohammad Areeb Siddiqui

Reputation: 10179

c# - How to close the main form without letting the application close?

What i want to do:
->Open a MDI form
->Close the projects main form
->Without closing the application

What i have done:

frmMain fm = new frmMain();
fm.Show();
this.Close()

Any help would be appreciated! :)

Upvotes: 1

Views: 3705

Answers (3)

Godeke
Godeke

Reputation: 16281

If you actually wish to close the main form, but leave the application running, you can make your default class launch the application context:

using(MyContext myContext = new MyContext())
{
    Applicaton.Run(myContext);
}

where MyContext inherits from ApplicatonContext.

Your application context can then load and close forms as needed. I do this with one project where I have the context launch a login form. Only after it is completed successfully does the main form get loaded. I also allow the "logging out" from the program to be handled by terminating the main form and reloading the login form.

EDIT: From the comments, it may be that all you are looking for is .Hide(). This doesn't cause your form to unload and a call to .Show() will restore it (for example, you can use a timer or another form holding a reference to your main form to make the call). I prefer to use an ApplicationContext because it takes the responsibility for keeping your program in memory away from a UI element which the user may attempt to close.

Upvotes: 2

James
James

Reputation: 1036

What I did to get around this is:

this.Hide()

Probably not the best way to do this, but still.

You could even get it back by calling

this.Show()

Upvotes: 2

YoryeNathan
YoryeNathan

Reputation: 14522

You can use the Hide method.

Try doing this:

frmMain fm = new frmMain();
this.Hide();
fm.Show();

Or:

frmMain fm = new frmMain();
this.Hide();
fm.ShowDialog();
this.Show();

The latter will open the window, and once it is closed, the previous window will reappear.

Upvotes: 2

Related Questions