private bool ShowChildrenForm(string p_ChildrenFormText)
{
int i;
//依次检测当前窗体的子窗体
for (i = 0; i < this.MdiChildren.Length; i++)
{
//判断当前子窗体的Text属性值是否与传入的字符串值相同
if (this.MdiChildren[i].Text == p_ChildrenFormText)
{
//如果值相同则表示此子窗体为想要调用的子窗体,激活此子窗体并返回true值
this.MdiChildren[i].Activate();
return true;
}
}
//如果没有相同的值则表示要调用的子窗体还没有被打开,返回false值
return false;
}
在使用MDI子窗体时,如果仅仅是使用 from.show() 代码,那么我们单击几次菜单,就会打开几个同样的子窗体。可以用这段代码防止这种情况。{
int i;
//依次检测当前窗体的子窗体
for (i = 0; i < this.MdiChildren.Length; i++)
{
//判断当前子窗体的Text属性值是否与传入的字符串值相同
if (this.MdiChildren[i].Text == p_ChildrenFormText)
{
//如果值相同则表示此子窗体为想要调用的子窗体,激活此子窗体并返回true值
this.MdiChildren[i].Activate();
return true;
}
}
//如果没有相同的值则表示要调用的子窗体还没有被打开,返回false值
return false;
}
首先添加一个函数,这个函数用于检测指定的子窗体是否已经打开,如果打开则激活这个子窗体,否则返回false值
然后在调用子窗体的方法中写入如下代码
if ( ! ShowChildrenForm("子窗体的Text属性值") )
{
Form newForm = new Form();
newForm.MdiParent = this;
newForm.Show();
}
{
Form newForm = new Form();
newForm.MdiParent = this;
newForm.Show();
}
这样在调用子窗体时,会判断是否已经打开此窗体的相同实例,如果是则激活打开的窗体,不是的话才会再打开一个新的实例。