1)FormMain.cs
后台代码 FormMain.cs
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
// 主窗体启动时,在panel中扒纯先显示Form1
private void FormMain_Load(object sender, EventArgs e)
{
Form1 f1 = new Form1(this);
f1.TopLevel = false;
panel1.Controls.Add(f1);
f1.Show();
谈或 }
// 添加一个pubilc 方法:在panel中显示Form2
public void ShowForm2()
{
Form2 f2 = new Form2();
f2.TopLevel = false;
panel1.Controls.Add(f2);
f2.Show();
}
}
}
2)Form1
后台代码 Form1.cs
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
含此伍 InitializeComponent();
}
FormMain frmMain;
// 添加一个构造函数,传入 FormMain
public Form1(FormMain frmMain)
: this()
{
this.frmMain = frmMain;
}
// 关闭Form1,显示Form2
private void button1_Click(object sender, EventArgs e)
{
this.Close();
frmMain.ShowForm2();
}
}
}
3)Form2,没有任何改变
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
}
}
4)运行
点击按钮后