The application is stopped to terminate when the starting window is closed
In the absence of multiple windows, the starting window (Form1) is closed when another window (Form2) is displayed. The goal is to keep the application run even after closing Form1.
Answer:
The problem is the default behavior of the main application thread. This thread is usually terminated when the start (program.cs) is closed. To solve this problem:
Modify the code in Program.cs to monitor the closing event of the window:
<code class="language-csharp">[STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var main = new Form1(); main.FormClosed += new FormClosedEventHandler(FormClosed); main.Show(); Application.Run(); }</code>
<code class="language-csharp">static void FormClosed(object sender, FormClosedEventArgs e) { ((Form)sender).FormClosed -= FormClosed; if (Application.OpenForms.Count == 0) Application.ExitThread(); else Application.OpenForms[0].FormClosed += FormClosed; }</code>
If there are no more open windows, the application is terminated.
The above is the detailed content of How to Keep a Windows Forms Application Running After Closing the Startup Form?. For more information, please follow other related articles on the PHP Chinese website!