Live Chat Icon For mobile
Live Chat Icon

How do I check to see if a child form is already displayed so I don’t have two instances showing?

Platform: WinForms| Category: MDI

Here are two ways you can do this.

i)
Within the parent MDI form, use code such as this:

	// MyChildForm is the one I’m looking for
	MyChildForm childForm = null;
	foreach(Form f in this.MdiChildren) 
	{
		if(f is MyChildForm) 
		{
			// found it
			childForm = (MyChildForm) f;
			break;
		}
	}

	if( childForm != null)
	{
		childForm.Show();
		childForm.Focus();
	}
	else
	{
		childForm = new MyChildForm();
		childForm.MdiParent = this;
		childForm.Show();
		childForm.Focus();
	}

ii) Here is a second solution suggested by John Conwell that 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 frmChildForm childForm;
	public static ChildForm GetInstance
	{
		if (childForm == null)
			childForm = new frmChildForm;
		return childForm;
	}

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

	frmChildForm childForm = frmChildForm.GetInstance();
	childForm.MdiParent = this;
	childForm.Show();
	childForm.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.

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.