You cannot do it during the single run-time of the instance of
System.Windows.Forms.Application
.
When you call
Application.Run
, its parameter defined the instance of the
System.Windows.Forms.Form
which assumes the role of Main Form. All other forms will be non-main. Every time you close the main form, Application is closed. It means,
Application.Run
exits. Is does not happens with any other form unless you explicitly call
Application.Exit
.
So, in principle you can use tricky technique inside your application's entry point (normally, this is the
Main
method):
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form firstMain = new FirstMain();
Form secondMain = new SecondMain();
Application.Run(firstMain);
if (CertainConditionYouMightDesign(firstMain)
Applicatin.Run(secondMain);
}
This certainly will work but…
don't do it!
This will be a pretty big abuse of the intended use of the Forms application.
You can imitate desired effect hiding forms instead of closing. Naturally, you need to preserve a way to exit application explicitly. Every time the form is closed, you need to make sure another form is shown. This technique is the most usual and successful.
This is how to hide a form on attempt to close it:
class SecondMain : Form {
protected override void OnFormClosing(FormClosingEventArgs e) {
if (e.CloseReason == CloseReason.UserClosing) {
e.Cancel = true;
Hide();
}
}
}
I'm not showing the logic of automatic closing one form and showing another one. Basically, you should create some interface and implement it on each form. This interface should have one or two methods for communications between forms, so the form would tell to each other: "I'm closing, you show yourself and go to top". In the beginning of the forms life cycle, you need to pass the interface reference for the other form to each other. (You could directly pass instances of the forms to each other and have some public methods for such interaction, but this is a violation of isolation principles; delegates is the most safe technique; you should not pass more access then it's really needed.)
This technique is especially convenient thanks to using of
partial
class declaration. You can create more separate files for the same class and add one more partial declaration devoted to this effect. For more information on form collaboration, see my past answer here
How to copy all the items between listboxes in two forms[
^]. Consider other solutions and see the discussion.
Now, final advice:
do not do it all! Change the general design. Make one and only one main form, fill it with some
TabControl
and make some tabs. What were you separate windows make a separate tab pages. Simple and civilized. More than one form is not really nice solution.
—SA