C# Allow only 1 instance of a form to be opened

While working on some programs dealing with multiple forms, I ran into an issue where I would end up with more than 1 instance of the same form being created. This came up when using a form as an MDI parent and then trying to open another form as a child to the parent form. When the child form would open, you could continue opening new instances of that same form while the one prior was still opened.

The code below will check to see if it already exists and if it doesn’t assign the new form as a child to the mdi parent form and open it.

 

//Code that handles Child forms. May be adding more code to this down the road for customization.
        //No need to write the same code for every form
        private void CreateMDIChild(Form childForm)
        {
            //Checks if child form already exists. Only open if it does not exist in the collection
            FormCollection allForms = Application.OpenForms;
            bool formOpened = false; //Assume that this form does not already exist
 
            foreach (Form frm in allForms)
            {
                if (frm.Name == childForm.Name)
                {
                    //Tried to open form here however it throws an error about the collection being modified. So we create a bool and if the form exists
                    //set it to true
                    formOpened = true;
                }
            }
            //As long as formOpened is false we can open the new form as a child form to the parent
            if (formOpened == false)
            {
                childForm.MdiParent = this;
                childForm.Show();
            }
        }

Using the method

private void loginRegisterToolStripMenuItem_Click(object sender, EventArgs e)
        {    
            CreateMDIChild(new frm_LoginRegister());
        }

Leave a Reply

Your email address will not be published. Required fields are marked *