Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I ensure that no more than one instance of a child form is created?

Here are two ways you can do this.

1. Within the parent MDI form, use code such as this:

// ChildForm is type being created or shown

ChildForm childForm = null; 
foreach ( Form f in MdiChildren ) 
  if ( f is ChildForm ) 
  { 
    childForm = (ChildForm) f; 
    break; 
  } 

if( childForm == null ) 
{ 
  childForm = new ChildForm(); 
  childForm.MdiParent = this; 
}

childForm.Show(); 
childForm.Focus();

2. A second solution implements a singleton pattern on the child form.

In the MDI Child form put this code in (where frmChildForm is the MDI child form you want to control)

// Used for singleton pattern 
static ChildForm childForm; 
public static ChildForm GetInstance 
{ 
  if ( childForm == null ) 
    childForm = new ChildForm(); 
  return childForm; 
}

In the Parent MDI form use the following code to call the child MDI form

ChildForm form = GetInstance(); 
form.MdiParent = this; 
form.Show(); 
form.BringToFront();

The first time this code is called, the static GetInstance method will create and return an instance of the child form. Every other time this code is called, the GetInstance method will return the existing instance of the child from, stored in the static field childForm. If the child form instance is ever destroyed, the next time you call GetInstance, a new instance will be created and then used for its lifetime.

Also, if you need constructors or even overloaded constructors for your MDI Child Form, just add the needed parameters to the GetInstance function and pass them along to the class constructor.

George Shepherd, Syncfusion, and John Conwell



Page view counter