Tutorials Navigation

Tutorials :: New :: Popular :: Top Rated

Tutorials: 18,326 Categories: 12

Total Tutorial Views: 41,304,134

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

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

Category: PC Tutorials

Submitted By: Zero1UP

Date Added:

Comments: 2

Views: 3,910

Related Forum: PC Building Forum

Share:

In this example I will show you how to only allow one instance of a form to be open when using MDI parent forms.

An MDI parent form acts as a container in which you are able to open other forms inside of. If you have a multiform application this can help with screen clutter since it will be self contained.

To make a form an MDI parent head over to the form properties and set IsMdiContainer to true.

Any form that you wish to open in this form, you would set their mdiParent to this form. However the code below will handle this for you.


       //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)
                {
                    //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());
        }

Ratings

Current rating: 2.00 by 4 users
Please take one second and rate this tutorial...

Not a Chance
1
2
3
4
5
6
7
8
9
10
Absolutely

Comments

"C# Allow only 1 instance of a form to be opened" :: Login/Create an Account :: 2 comments

If you would like to post a comment please signin to your account or register for an account.

KatsumiPosted:

Halo Seems straightforward, thanks a bunch


That's not the word i would use to describe programming lol

HaloPosted:

Seems straightforward, thanks a bunch