Prevent same child window multiple times in MDI form

后端 未结 2 1617
遇见更好的自我
遇见更好的自我 2021-02-06 13:13

I am working on c# desktop application, In MDI form the same child window getting opened when you click on menu, while first instance of that window is present. How can I preven

相关标签:
2条回答
  • 2021-02-06 14:05

    You can check if the form has been opened already:

      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();
        ...
      }
    
    0 讨论(0)
  • 2021-02-06 14:14

    Maybe this can help you:

    public static bool formOpened = false;   // it is global boolean
    Form2 instance;
    

    When you open your form:

    if(formOpened == false)
    {
       instance = new Form2();
       instance.Show();
       formOpened = true;
    }
    else
    {
        instance.Focus();
    }
    

    One more thing is after your Form2 is been closed, you should set the value of formOpened to false;

    0 讨论(0)
提交回复
热议问题