C# 隐藏表单后如何再次显示表单?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13233451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 07:51:01  来源:igfitidea点击:

How to show a form again after hiding it?

c#winformsformsminimizemaximize-window

提问by Oktay

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 时,我隐藏了 form1。但是,当我尝试使用按钮从 form2 再次显示 form1 时,它不起作用。我的form1代码是:

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

Inside form2 code:

里面的form2代码:

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最大化它。

Form2.ActiveForm.WindowState = FormWindowState.Maximized;

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

但是我尝试的方式再次不起作用。这些方法有什么问题?

采纳答案by Marco

You could try (on Form1 button click)

您可以尝试(在 Form1 按钮上单击)

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

or (it should work)

或(它应该工作)

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

回答by Furqan Safdar

Preserve the instance of Form1and use it to Showor Hide.

保留 的实例Form1并将其用于ShowHide

回答by Mauro Sampietro

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

如果您像这样显示 form2,您可以通过 Owner 属性从 Form2 访问 Form1:

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

请注意这种方式您不会被迫使用 ShowDialog 因为隐藏和显示逻辑可以在 Form2 中移动

回答by user3569147

This method is the one that I find works the best for me

这种方法是我发现最适合我的方法

Primary Form

初级形式

Form2 form2 = new Form2(this);

Secondary Form

次要表格

private Form Form1
public Form2(Form Form1)
{
    InitializeComponent();
    this.Form1 = Form1;
    Form1.Hide();
}

Later on when closing

稍后关闭时

private void btnClose_Click(object sender, EventArgs e)
{
    Form1.Show();
    this.Close();
}