场景切换不正确

Scenes aren't switching properly

所以我在 Windows 表单应用程序中有两个场景,它们应该切换。但是,它无法正常工作。这是 Form1 的代码:

using System;
using System.Windows.Forms;

namespace Chat_Room {
    public partial class SceneOne : Form {
        public SceneOne() {
            InitializeComponent();
        }
        private void createRoomButton_Click(object sender, EventArgs e) {
            Form2 scene = new Form2();
            scene.Show();
            this.Close();
        }
    }
}

我知道,这是一个小问题,但是我已经把所有的代码都放在了一个表格中,然后我决定把它分成两个,但是一旦我移动了代码,它就停止切换了(现在它只关闭第一个)。是的,第二种形式是 Form2。

来自msdn - Form.Close

When a form is closed, all resources created within the object are closed and the form is disposed

因此,当您调用 this.Close() 时,scene 也会按“在对象 中创建”的方式处理。

根据 this discussion,也许你应该尝试这样的事情:

this.Hide();
Form2 f = new Form2();
f.Show();

你不应该使用 this.Close() 因为那将处理表格

看看Form.Designer.cs

protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

而不是使用 this.Close() 尝试隐藏表单 this.Hide

重点是如何开始 Application

只需像这样修改您的 Main 方法:

namespace Chat_Room 
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
//Need this, because if you do it in your Run method, appication will closes immediatly after you close the form.
            (new SceneOne()).Show(); 
            Application.Run(); 
        }
    }
}

在你最后一个场景的关闭事件中,调用Application.Ext()方法。

想了解更多,MSDN参考:

public static void Run(
    Form mainForm
)

此方法将事件处理程序添加到 Closed 事件的 mainForm 参数。事件处理程序调用 ExitThread 来清理应用程序。

也来自MSDN 如果您正在使用

public static void Run()

在 Windows 窗体中,调用 Exit 方法或在 运行 主消息循环的线程上调用 ExitThread 方法时,此循环将关闭.

所以如果你选择Application.Run()(所以没有参数),你必须调用Application.Exit方法来关闭应用程序。

所以需要