C# 窗体显示/隐藏
本文关键字:隐藏 显示 窗体 | 更新日期: 2023-09-27 18:30:58
在 VB.NET 中,您可以自由隐藏/显示/显示对话框(用于全新表单)。但在 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();
另一种更冗长的方法是跟踪自己在应用程序中使用变量隐藏/显示的表单。这需要格外小心地正确处理全局变量变得无效的各种情况(如果用户有效地关闭表单而不是隐藏它怎么办?
这是一个可以使用 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似乎好多了。