Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show a form again after hiding it?

I have two forms. I need to open a second form with a button. When I open form2 I hide form1. However when I try to show form1 again from form2 with a button it doesn't work. My form1 code is:

Form2 form2 = new Form2();        
form2.ShowDialog();

Inside form2 code:

Form1.ActiveForm.ShowDialog();

or

Form1.ActiveForm.Show();

or

form1.show(); (form1 doesn't exist in the current context)

doesn't work. I do not want to open a new form

Form1 form1 = new Form1();   
form1.ShowDialog();

I want show the form which I hided before. Alternatively I can minimize it to taskbar

this.WindowState = FormWindowState.Minimized;

and maximize it from form2 again.

Form2.ActiveForm.WindowState = FormWindowState.Maximized;

however the way I am trying is again doesn't work. What is wrong with these ways?

like image 257
Oktay Avatar asked Nov 05 '12 13:11

Oktay


People also ask

How do you display a form in C#?

Press F5 to build and run the application. Click on the button in the main form to display the sub form. Now, when you press the button in the sub form, the form will be hidden.

How do you hide a form?

On each click, we check if the form's display property is set to none . If the form is already hidden, we show it by setting its display property to block . On the other hand, if the form is not hidden, we hide it by setting its display property to none .

How do I open a Form 2 Form 1?

Now go to Solution Explorer and select your project and right-click on it and select a new Windows Forms form and provide the name for it as form2. Now click the submit button and write the code.

How do you change from one form to another in C#?

Inside Form1, there is a button SwitchFormButton, which has below code: Form2 f2 = new Form2(); f2.


3 Answers

You could try (on Form1 button click)

Hide();
Form2 form2 = new Form2();        
form2.ShowDialog();
form2 = null;
Show();

or (it should work)

Hide();
using (Form2 form2 = new Form2())       
    form2.ShowDialog();
Show();
like image 152
Marco Avatar answered Nov 11 '22 10:11

Marco


Preserve the instance of Form1 and use it to Show or Hide.

like image 26
Furqan Safdar Avatar answered Nov 11 '22 09:11

Furqan Safdar


You can access Form1 from Form2 throught the Owner property if you show form2 like this:

form2.ShowDialog( form1 )

or like this:

 form2.Show( form1 )

Notice this way you are not forced to use ShowDialog cause hide and show logic can be moved inside Form2

like image 44
Mauro Sampietro Avatar answered Nov 11 '22 11:11

Mauro Sampietro