C# 窗体 Show/Hide

C# Forms Show/Hide

在VB.NET中,可以自由Hide/Show/ShowDialog(换个新形式)。但是在 C# 中,您总是必须创建新的表单实例才能执行此操作。即使您之前隐藏的表单也无法显示,您必须重新创建新实例。导致您之前隐藏的表单将 运行 作为后台进程,直到您将其杀死。

我的问题是,当我使用表单标题栏中的默认退出关闭当前表单时,如何创建一个函数来取消隐藏不需要新实例的表单。

编辑:我自己解决了。这只是令人困惑。 c# 和 vb.net 之间的区别在于我永远不必在 vb.net 中使用 form_closed。为什么我在c#里总是看到。

您始终可以在 C# 中显示隐藏窗体。有很多方法。
例如,您可以检查 Application.OpenForms 集合,该集合跟踪您的应用程序拥有但仍未关闭的所有表单。 (隐藏窗体未关闭)。这种方法意味着您需要在集合 OpenForms

中包含的表单之间识别您的表单
MyFormClass f = Application.OpenForms.OfType<MyFormClass>().FirstOrDefault();
if ( f != null) f.Show();

另一种更冗长的方法是使用应用程序中的变量来跟踪 hide/show 的表单。这需要格外小心地正确处理全局变量失效的各种情况(如果用户有效地关闭了表单而不是隐藏它怎么办?)

这是一个您可以使用 LinqPAD 轻松测试的示例

// Your form instance to hide/show
Form hidingForm = null;

void Main()
{
    Form f = new Form();
    Button b1 = new Button();
    Button b2 = new Button();
    b1.Click += onClickB1;
    b2.Click += onClickB2;

    b1.Location = new System.Drawing.Point(0,0);
    b2.Location = new System.Drawing.Point(0, 30);
    b1.Text = "Hide";
    b2.Text = "Show";

    f.Controls.AddRange(new Control[] {b1, b2});
    f.ShowDialog();
}

void onClickB1(object sender, EventArgs e)
{
    // Hide the global instance if it exists and it is visible
    if(hidingForm != null && hidingForm.Visible)
        hidingForm.Hide();
}

void onClickB2(object sender, EventArgs e)
{
    // Create and show the global instance if it doesn't exist
    if (hidingForm == null)
    {
        hidingForm = new Form();
        hidingForm.Show();

        // Get informed here if the user closes the form
        hidingForm.FormClosed += onClosed;
    }
    else
    {
        // Show the form if it is not visible
        if(!hidingForm.Visible)
            hidingForm.Show();
    }
}
void onClosed(object sender, FormClosedEventArgs e)
{
    // Uh-oh.... the user has closed the form, don't get fooled...
    hidingForm = null;
}

嗯,OpenForms 似乎好多了。