Dumbo
Dumbo

Reputation: 14102

How to check from a child form if another form is running in it's MDI parent?

I have a MDI form. I want to check within a running child of this form if another form is running. Something like:

    if (this.MdiParent.MdiChildren.Contains(MyForm2))
    {
        //Do Stuff
    }

Where MyForm2 is the name (class name) for the form I am looking for. The compiler says something like "Class name is not valid at this point".

How to do this properly? Please note that I can have multiple instances of "MyForm2" running at that momemnt (Well, with different instance names!)

Upvotes: 1

Views: 5609

Answers (2)

competent_tech
competent_tech

Reputation: 44921

Just create a loop to cycle through the MdiChildren collection to see if any form of the specified Type exists. Contains requires a specific instance to return valid data:

        foreach (var form in this.MdiParent.MdiChildren)
        {
            if (form is MyForm2)
            {
                // Do something. 

                // If you only want to see if one instance of the form is running,
                // add a break after doing something.

                // If you want to do something with each instance of the form, 
                // just keep doing something in this loop.
            }
        }

Upvotes: 2

Scott Rippey
Scott Rippey

Reputation: 15810

You need to check the type of each child.

For example you can use the is keyword (more info) to determine if a child is the correct type:

if (this.MdiParent.MdiChildren.Any(child => child is MyForm2))
{
}

The .Any() method requires a reference to System.Linq. Read more about Any()

Upvotes: 2

Related Questions