在开发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();}}}/// <summary>/// 用窗体名称字符串 初始化一个窗体/// </summary>/// <param name="formName"></param>/// <returns></returns>public static Form InitializeFormByName(string formName, string nameSpace = null){// 字符串是完整的类名,包括命名空间try{// 使用反射创建窗体实例//Type formType = Type.GetType("WinformDemo." + formName);Type formType = string.IsNullOrEmpty(nameSpace) ? Type.GetType("WinformDemo." + formName) : Type.GetType($"{nameSpace}." + formName);if (formType != null){return (Form)Activator.CreateInstance(formType);}}catch (Exception ex){// 处理异常,例如类型未找到或创建实例失败Console.WriteLine("Error: " + ex.Message);}return null;}
程序实例链接:https://download.csdn.net/download/lvxingzhe3/89422924