Home >Backend Development >C++ >How to Keep a Windows Desktop Application Running After Closing the Main Form?

How to Keep a Windows Desktop Application Running After Closing the Main Form?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-29 10:26:38196browse

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:

  1. Attach a FormClosed Event Handler: Add an event handler to the FormClosed event of your main form.
  2. Manage Open Forms: Within the event handler, remove the handler from the closed form. Then, check the number of open forms using 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn