In. in the net WinForm program, if the Form is directly started as the main window, the main window cannot be closed because it maintains a Windows message loop, once it is closed, the entire application is declared to end, so the newly opened window is automatically closed. Therefore, the window to be closed cannot be created using Application. Run.
To open another window while closing one window, follow these steps:
Declare a public bool variable in the first window and assign the value true:
For example, public bool closeflag = true;
Run the second window in the program class. The main code is as follows:
Application. EnableVisualStyles ();
Application. SetCompatibleTextRenderingDefault (false );
Form1 form1 = new Form1 ();
Form1.ShowDialog (); // mode window. Run Form1 first.
If (from1.closeflag = false)
{
Application. Run (new Form2 ());
}
Then, assign the closeflag value to false in the closed controls of Form1 (such as the button or something) and call this. close (); close the first window.
(Reference)