Bernice
Bernice

Reputation: 2592

How can I access a minimized form from another form without creating an instance?

In my winforms application I am using form.ActiveForm from another form a lot of times. This is because I don't want a new instance of the form but just to bring the form to the front or to set it's components differently. I noticed however that when I minimize the form, form.ActiveForm returns a NullReferenceException. What can I do so that I can access this minimized form? There doesn't seem to be a method for it. Is there another way to do this?

Upvotes: 1

Views: 232

Answers (3)

Tara McGrew
Tara McGrew

Reputation: 2027

Use Application.OpenForms to find a form of the correct type:

foreach (var f in Application.OpenForms)
{
    if (f is MyForm)
    {
        // do something...
        break;
    }
}

Upvotes: 1

Jonathan Wood
Jonathan Wood

Reputation: 67223

Save a reference to the minimized form. If you like, you can store it with the second form by creating a public property:

public MyForm myForm;

And then set it:

MyForm frm = new MyForm();
frm.myForm = (first form reference here);

And then the second form can directly reference the first form using myForm.

Upvotes: 0

Brett Wolfington
Brett Wolfington

Reputation: 6627

Store the minimized form as a field in your primary form, and access it that way. If the form is minimized, then it is not "active." Using the field, you will still be able to access it, however.

Upvotes: 1

Related Questions