如何在单击Button1时第二次打开Form2?

时间:2010-04-28 05:38:58

标签: c# forms

我有代码:

private void Button1_Click (object sender, EventArgs e)
(
    Form2 f2 = new Form2 ();
    f2.Show ();
)

如果单击按钮1第二次没有打开,如果它打开,如何制作表格2?

抱歉英语不好

5 个答案:

答案 0 :(得分:2)

您必须确保只创建了一个Form2实例。一种方法是将对象声明和实例化移动到私有变量,在click事件处理程序中只需调用Show()方法:

private Form2 f2 = new Form2();
private void Button1_Click (object sender, EventArgs e)
(
    if(f2 == null) 
    {
      f2 = new Form2();
    }
    f2.Show ();
)

答案 1 :(得分:2)

与现有答案类似,但有一个额外的事件处理程序:

private Form f2 = null;
private void Button1_Click (object sender, EventArgs e)
{
    if (f2 == null)
    {
        f2 = new Form2();
        // Make sure we don't try to re-show a closed form
        f2.FormClosed += delegate { f2 = null; };
    }
    f2.Show ();
}

答案 2 :(得分:1)

假设您的主表单类是MyForm,请更新您的代码,如下所示。我们的想法是只维护Form2的单个实例。

public partial class MyForm: Form
{
    public MyForm()
    {
        InitializeComponent();
    }

    private Form2 f2;
    private void Button1_Click (object sender, EventArgs e)
    (    
        if (null == f2 || f2.IsDisposed)
            f2 = new Form2();

        f2.Show ();
    )
}

答案 3 :(得分:0)

我没有检查Visible属性是否适用于Form,但你可以尝试这个。

public partial class MyForm: Form
    {
        public MyForm()
        {
            InitializeComponent();
        }

        Form2 f2 = null;
        private void Button1_Click (object sender, EventArgs e)
        (    
            if(f2 == null)
              f2 = new Form2();
            if(!f2.Visible)
              f2.Show ();
        )
    }

答案 4 :(得分:0)

此代码将打开表单。 如果之前的表格未在申请中打开。

private void button1_Click(object sender, EventArgs e)
    {
        bool result = false;

        foreach (Form form in Application.OpenForms)
        {
            if (form.GetType() == typeof(Form2))
                result = true;
        }

        if (result == false)
            new Form2().Show();
    }