Home >Backend Development >C++ >How to Keep a Windows Desktop Application Running After Closing the Main Form?
Keeping Your Windows Desktop App Running After Closing the Initial Form
Many Windows desktop applications require continued operation even after the initial (startup) form is closed. Simply hiding the startup form using the Hide()
method isn't ideal, as the application remains active even with all forms hidden.
A more elegant solution involves adjusting the application's entry point in Program.cs
. The default behavior automatically ends the application when the main form closes. Here's how to change that:
FormClosed
event of your main form.Application.OpenForms.Count
. If no forms are open, gracefully exit the application using Application.ExitThread()
. Otherwise, attach the event handler to the next open form.Here's the modified Program.cs
code:
<code class="language-csharp"> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var main = new Form1(); main.FormClosed += FormClosed; // Attach the event handler main.Show(); Application.Run(); } static void FormClosed(object sender, FormClosedEventArgs e) { ((Form)sender).FormClosed -= FormClosed; // Detach from closed form if (Application.OpenForms.Count == 0) Application.ExitThread(); // Exit if no forms remain else Application.OpenForms[0].FormClosed += FormClosed; // Attach to the next form }</code>
This refined approach ensures your application continues running as expected after closing the initial form, providing a smoother and more controlled user experience, and cleanly exiting only when all forms are closed.
The above is the detailed content of How to Keep a Windows Desktop Application Running After Closing the Main Form?. For more information, please follow other related articles on the PHP Chinese website!