C# 设置子窗口,并且解决窗体显示问题与多次打开问题
实例:
本例讲解的是在C#中如何设置主窗口和子窗口,并解决一下奇葩问题,问题如下:
1、每次打开子窗口的位置均会因为有Menistrip而有不同的位移,循环往复;
2、多次打开同子窗口,子窗口对象被多次创建;
3、其它未知,后期补上;
实现方式:
1、主窗口的设置
private void main_Load(object sender, EventArgs e) { //设置主窗口为MDI容器 this.IsMdiContainer = true; //设置窗口默认状态 this.WindowState = FormWindowState.Normal; //设置窗口位置状态 this.TopLevel = true; //设置子窗口内容排列方式,当前为居中 this.StartPosition = FormStartPosition.CenterParent; }
2、Menustrip的菜单Click事件
//实例化子窗口对象 HostipalInfo HostipalInfofrm = new HostipalInfo(); //关闭窗口位置状态 HostipalInfofrm.TopLevel = false; //这是一个判断方法,方法内容在下方会提到 if (!ShowChildrenForm(HostipalInfofrm.Text)) { //设置子窗口对象的主窗口是哪个 HostipalInfofrm.MdiParent = this; /设置窗口默认状态 HostipalInfofrm.StartPosition = FormStartPosition.Manual; //显示子窗口对象 HostipalInfofrm.Show(); } //设置主窗口的宽度与高度,加值为边框,涵盖内容的实际宽度、高度 this.Width = HostipalInfofrm.Width + 20; this.Height = HostipalInfofrm.Height + 90;
上面用到的方法ShowChildrenForm
private bool ShowChildrenForm(string p_ChildrenFormText) { int i; //依次检测子窗口,关闭全部打开子窗口 //this.MdiChildren.Length 用于统计子窗口数量 for (i = 0; i < this.MdiChildren.Length; i++) { this.MdiChildren[i].Close(); } //返回false值 return false; }