且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

当我关闭启动表单时,如何防止应用程序终止?

更新时间:2023-01-26 10:58:14

Program.cs 中自动生成的代码被编写为在启动窗口关闭时终止应用程序.您需要对其进行调整,使其仅在没有更多窗口时才终止.像这样:

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;
    }