简体   繁体   中英

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! :)

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.

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM