下面的代码片断假设你的多文档应用程序中包含一个toolbar。当你点击toolbarbutton1 按钮时,将会创建并显示一个 patients 子窗口。下面的代码在单机事件时发生。
private void toolbar1_buttonclick(object sender,
system.windows.forms.toolbarbuttonclickeventargs e)
{
// a flag to store if the child form is opened or not
bool found = false;
if (e.button == toolbarbutton1)
{
// get all of the mdi children in an array
form[] charr = this.mdichildren;
if (charr.length == 0) // no child form is opened
{
patients mypatients = new patients();
mypatients.mdiparent = this;
// the startposition property is essential
// for the location property to work
mypatients.startposition = formstartposition.manual;
mypatients.location = new point(0,0);
mypatients.show();
}
else // child forms are opened
{
foreach (form chform in charr)
{
if (chform.name == "patients")
// one instance of the form is already opened
{
chform.activate();
found = true;
break; // exit loop
}
else
found = false; // make sure flag is set to
// false if the form is not found
}
if (found == false)
{
patients mypatients = new patients();
mypatients.mdiparent = this;
// the startposition property is essential
// for the location property to work
mypatients.startposition = formstartposition.manual;
mypatients.location = new point(0,0);
mypatients.show();
}
}
}
}
这样,就实现了一个单窗口实例的解决方案。
