在c#中切换两个Form

本文关键字:两个 Form | 更新日期: 2023-09-27 18:17:54

我有两个表单: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;
    }

}

Form2:

public partial class Form2: Form{公共Form2 (){InitializeComponent ();}

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

}

在c#中切换两个Form

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

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