在C#中切换两个Form?

时间:2013-06-10 11:51:31

标签: c# forms

我有两种形式:Form1和Form2。 Form1有button1,Form2有button2。 当项目运行时,将显示Form1,然后单击button1,然后显示Form2并隐藏form1。如果我单击button2,则Form1可见,Form2关闭!

Form1中:

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


    private void button1_Click(object sender, EventArgs e)
    {
        this.Hide();
        Form2 fo = new Form2();
        fo.Visible = true;
    }


}

窗体2:

公共部分类Form2:表格     {         公共Form2()         {             的InitializeComponent();         }

    private void button1_Click(object sender, EventArgs e)
    {
        Form1 f1 = new Form1();
        f1.Visible = true;
        this.Close();
    }


}

2 个答案:

答案 0 :(得分:0)

void Button1_Click(...)
{
   Form2 f2=new Form2(form1);
   f2.ShowDialog();
   form2.Hide();
}

void Button2_Click(...)
{
   this.Hide();
   form1.Show();
}

答案 1 :(得分:0)

假设Form1是传递给program.cs中的Application.Run()的“启动表单”:

public partial class Form1 : Form
{

    private void button1_Click(object sender, EventArgs e)
    {
        this.Hide();

        foreach (Form frm in Application.OpenForms)
        {
            if (frm is Form2)
            {
                frm.Show();
                return;
            }
        }

        Form2 f2 = new Form2();
        f2.Show();
    }

}

使用:

public partial class Form2 : Form
{

    private void button1_Click(object sender, EventArgs e)
    {
        this.Hide();

        foreach (Form frm in Application.OpenForms)
        {
            if (frm is Form1)
            {
                frm.Show();
                return;
            }
        }
    }

}