How do I prevent the app from terminating when I close the startup form?

The auto-generated code in Program.cs was written to terminate the application when the startup window is closed. You’ll need to tweak it so it only terminates when there are no more windows left. Like this:

    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        var main = new Form1();
        main.FormClosed += new FormClosedEventHandler(FormClosed);
        main.Show();
        Application.Run();
    }

    static void FormClosed(object sender, FormClosedEventArgs e) {
        ((Form)sender).FormClosed -= FormClosed;
        if (Application.OpenForms.Count == 0) Application.ExitThread();
        else Application.OpenForms[0].FormClosed += FormClosed;
    }

Leave a Comment