如何在不创建新实例(表单)的情况下切换实例(表单)?

时间:2016-03-04 15:06:15

标签: c# winforms instance

我知道如何将表单切换为表单,但问题是从Form B切换到Form A时。它始终创建Form A的新实例。

我该如何避免这种行为?

1 个答案:

答案 0 :(得分:-2)

您要找的是Singleton

对于一个非常基本的方法,你可以采取这个:

public partial class Form1 : Form
{
    public static Form1 Instance { get; set; } //Create an Instance Object of your Window

    public Form1()
    {
        InitializeComponent();
    }

    //Your call to open the Window
    private void OpenForm2()
    {
        if (Form2.Instance == null)//Check if Form2 has already been created
        {
            //if not: go create a new one !
            Form2.Instance = new Form2();
        }
        //Instance of Form2 is already created => open that one            
        Form2.Instance.Show();            
    }
}

public partial class Form2 : Form
{
    public static Form2 Instance { get; set; }

    public Form2()
    {
        InitializeComponent();
    }
}