在开发Winform项目中,经常会要切换不同的窗体。通常程序都有一个主窗体,在切换窗体时往往需要关闭其他子窗体,这个实例就来介绍MDI主窗体内嵌子窗体的实现方法。
MDI主窗体要设置一个比较重要的属性,IsMdiContainer=true。子窗体的 formChild.MdiParent设置成为主窗体。
public MainForm()
{
InitializeComponent();
//设置改窗体为MDI容器(多文档界面容器),可嵌入多个子窗体
this.IsMdiContainer = true;
}
/// <summary>
/// 通过子窗体名,打开子窗体
/// </summary>
/// <param name="childFromName"></param>
/// <returns></returns>
private void OpenChildFrom(string childFromName)
{
bool bHave = false;
//子窗体已存在 则打开
foreach (Form formChild in this.MdiChildren)
{
if (formChild.Name == childFromName)
{
formChild.MdiParent = this;
formChild.Activate();
formChild.StartPosition = FormStartPosition.Manual;
//填满主窗体空间
formChild.Dock= DockStyle.Fill;
formChild.Show();
bHave = true;
}
else
{
formChild.Hide();
}
}
//子窗体不存在 创建并打开
if (bHave == false)
{
Form formChild = InitializeFormByName(childFromName);
if (formChild != null)
{
formChild.MdiParent = this;
formChild.StartPosition = FormStartPosition.Manual;
//填满主窗体空间
formChild.Dock = DockStyle.Fill;
formChild.Show();
}
}
}
程序实例链接:https://download.csdn.net/download/lvxingzhe3/89422924