5

我正在开发 c# 桌面应用程序,在 MDI 表单中,当您单击菜单时,会打开同一个子窗口,而该窗口的第一个实例存在。如何防止这些 MDI 表单中的多个子窗口实例?

4

2 回答 2

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();
    ...
  }
于 2013-06-29T11:01:56.130 回答
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;

于 2013-06-29T11:54:33.970 回答