以MDI形式多次阻止同一子窗口

本文关键字:窗口 MDI | 更新日期: 2023-09-27 18:20:26

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

以MDI形式多次阻止同一子窗口

您可以检查表单是否已经打开:

  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();
    ...
  }

也许这可以帮助您:

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;