There are two types of forms in the WinForms project - the main and child forms. The difference between them is that the main form is essentially an application, so when you close it, the application exits.
One solution is to hide the main form, instead of closing. This option is already written in the question. It is usually used when the main form is used in one way or another.
If the first form is not used in the future, then you can use 2 options:
1. Rules Program.cs
By default, the contents of the Program.cs file look like this:
using System; using System.Windows.Forms; namespace WindowsFormsApplication4 { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
As you can see, Form1 runs as an application and, when the form completes, it will exit from Main and the application.
To prevent this from happening, you can specify the sequence of form launch:
Application.Run(new Form1()); Application.Run(new Form2()); Application.Run(new Form3());
Then when you close the first form, the second will be called and so on until the last.
The disadvantage is difficult to transfer data between forms. Yes, you can define fields in the Program class, constructors with parameters in forms and transfer data through these fields and constructors parameters, but what if you need to return to one of the previous forms? To cut the complex logic of transitions into Main is not the best idea, to say the least.
2. Moving from forms to controls
WinForms has a great class UserControl . This is actually an empty control that you can fill with any content like a form.
After the set of such controls has been prepared, you just have to place them on the form with the Dock = DockStyle.Fill and controlling the value of the Conrol.Visible property, show the control you need at the moment. If you do not want to keep the control in memory, no one bothers to simply create it at the right time and display it, and after using and switching to a new control, unsubscribe from events, call Dispose() , remove all links and give it to the garbage collector. Only the gain from this is small, especially if you suddenly decide to show it again.
I forgot to write about another shortcoming of switching between forms via Main . Each new form will open a little bit in another place, which may be good for protection from auto-clicker programs, but this behavior is annoying for me as a user, and I think that it’s not just me.
You can also not transfer the form to Application.Run and run it without parameters. Then even closing all forms will not close the application. To exit, you will finally need to call Application.Exit - Lunar Whisper
Also a good option if you need to use different forms in the process.