Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent same child window multiple times in MDI form

Tags:

c#

.net

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 prevent these multiple instances of child windows in MDI form?

like image 280
n8coder Avatar asked Oct 03 '22 16:10

n8coder


1 Answers

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();
    ...
  }
like image 194
Dmitry Bychenko Avatar answered Oct 12 '22 11:10

Dmitry Bychenko