随着Winform项目越来越多,界面上显示的窗体越来越多,窗体管理变得更加繁琐。有时候我们要打开新窗体,然后关闭多余的其他窗体,这个时候如果一个一个去关闭就会变得很麻烦,而且可能还会出现遗漏的情况。这篇文章介绍了三种方式实现"Winform父窗体打开新的子窗体前,关闭其他子窗体"的方案。
代码:
public partial class MainForm : Form{private UserControl userControl;private UserControl1 userControl1;private UserControl2 userControl2;private Form1 form1;private Form2 form2;public MainForm(){InitializeComponent();this.IsMdiContainer = true;userControl1 = new UserControl1();userControl2 = new UserControl2();form1 = new Form1();form2 = new Form2();}private void btnForm1_Click(object sender, EventArgs e){方法一//ShowEmbeddedForm(1);方法二//form1.MdiParent = this;//OpenMdiForm(form1);//方法三OpenNewChildForm(form1);}private void btnForm2_Click(object sender, EventArgs e){方法一//ShowEmbeddedForm(2);方法二//form2.MdiParent = this;//OpenMdiForm(form2);//方法三OpenNewChildForm(form2);}/// <summary>/// 关闭所有子窗体/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btnHidden_Click(object sender, EventArgs e){panelForm.Controls.Clear();// 关闭所有子窗体for (int i = Application.OpenForms.Count - 1; i >= 0; i--){var openForm = Application.OpenForms[i];if(openForm!=this){openForm.Close();}}}/// <summary>/// 方法一:使用内嵌方式将控件放入到Panel中,放入前清空Panel中的控件/// </summary>private void ShowEmbeddedForm(int type){panelForm.Controls.Clear();if (type == 1){panelForm.Controls.Add(userControl1);}else if (type == 2){panelForm.Controls.Add(userControl2);}}/// <summary>/// 方法二:使用MDI实现父窗体每次只能显示一个子窗体/// 特点:子窗体内嵌到父窗体中/// </summary>/// <param name="子窗体名称"></param>private void OpenMdiForm(Form frm){//判断是否第一次显示窗体if (this.MdiChildren.Length == 1){frm.MdiParent = this;frm.Show();return;}foreach (Form children in this.MdiChildren){if (frm == children){//如果是现在就存在的子窗体就激活它children.Activate();}else{children.Close();if (frm == null || frm.IsDisposed){Type type = frm.GetType();frm = (Form)System.Activator.CreateInstance(type);frm.MdiParent = this;frm.Show();}else{frm.MdiParent = this;frm.Show();}}}}/// <summary>/// 方法三:使用OpenForms,在打开新窗体前关闭所有打开的子窗体/// </summary>/// <param name="newChildForm"></param>private void OpenNewChildForm(Form newChildForm){// 关闭所有其他的子窗体for (int i = Application.OpenForms.Count-1; i >=0; i--) {var openForm = Application.OpenForms[i];if (openForm != this && openForm != newChildForm){openForm.Close();}}// 打开新的子窗体if (newChildForm == null || newChildForm.IsDisposed){Type type = newChildForm.GetType();newChildForm = (Form)System.Activator.CreateInstance(type);newChildForm.Show();}else{newChildForm.Show();}}}
实例链接:https://download.csdn.net/download/lvxingzhe3/89249982