Reputation: 14102
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
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
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