Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show a form from another form

Tags:

c#

winforms

When I want to Display a form (C#) by clicking a button in another form I usually create an object from the form that I want to show and use the show method :

        Form2 f2 = new Form2();
        f2.Show();

or I work with the "Owner" :

        Form2 tempForm = new Form2();
        this.AddOwnedForm(tempForm);
        tempForm.Show();

the two ways generate the same results but what is the best and what are the differences between them?

like image 403
Mohamad Alhamoud Avatar asked Apr 11 '10 21:04

Mohamad Alhamoud


2 Answers

The only difference apart from the naming is that in the second you call AddOwnedForm, and in the first you do not. Looking at the documentation we see:

When a form is owned by another form, it is minimized and closed with the owner form. For example, if Form2 is owned by form Form1, if Form1 is closed or minimized, Form2 is also closed or minimized. Owned forms are also never displayed behind their owner form. You can use owned forms for windows such as find and replace windows, which should not be displayed behind the owner form when the owner form is selected.

So if you want this behavior of the forms being minimized together, and one always being shown above the other, use AddOwnedForm. If you don't want this behavior, don't use it.

like image 127
Mark Byers Avatar answered Oct 18 '22 14:10

Mark Byers


Microsoft uses Form f = new Form(); f.Show(); by default when creating a new Windows Forms project to show the main form, and there is probably negligible difference (in performance) between such methods. Using the Show() method, instead of just setting f.Visible = true; is also more logical.

When you use AddOwnedForm() you essentially lock the forms together in such way that when one form is minimized, the other is also. The form is also always displayed on top of the owning form, similar to a modal dialog.

like image 27
Daniel A.A. Pelsmaeker Avatar answered Oct 18 '22 14:10

Daniel A.A. Pelsmaeker