我正在使用c#桌面应用程序,在MDI窗体中,当您单击菜单时会打开相同的子窗口,而该窗口的第一个实例存在。 如何以MDI格式阻止子窗口的这些多个实例?
答案 0 :(得分:4)
您可以检查表单是否已经打开:
Form instance = null;
// Looking for MyForm among all opened forms
foreach (Form form in Application.OpenForms)
if (form is MyForm) {
instance = form;
break;
}
if (Object.ReferenceEquals(null, instance)) {
// No opened form, lets create it and show up:
instance = new MyForm();
instance.Show();
...
}
else {
// MyForm has been already opened
// Lets bring it to front, focus, restore it sizes (if minimized)
if (instance.WindowState == FormWindowState.Minimized)
instance.WindowState = FormWindowState.Normal;
instance.BringToFront();
if (instance.CanFocus)
instance.Focus();
...
}
答案 1 :(得分:0)
也许这可以帮到你:
public static bool formOpened = false; // it is global boolean
Form2 instance;
当您打开表单时:
if(formOpened == false)
{
instance = new Form2();
instance.Show();
formOpened = true;
}
else
{
instance.Focus();
}
还有一件事是在关闭Form2之后,你应该将formOpened的值设置为false;