我想知道如何使用 this.Close() 再次打开关闭的表单。每次我尝试使用 Mainmenu.Show() 打开关闭的表单时,异常都会引发错误“无法访问已处置的对象。对象名称:Mainmenu”。
我怎样才能再次打开它?
我想知道如何使用 this.Close() 再次打开关闭的表单。每次我尝试使用 Mainmenu.Show() 打开关闭的表单时,异常都会引发错误“无法访问已处置的对象。对象名称:Mainmenu”。
我怎样才能再次打开它?
当Close
在 a上调用该方法时,Form
您不能调用该Show
方法使表单可见,因为表单的资源已经被释放 aka Disposed
。若要隐藏窗体然后使其可见,请使用 Control.Hide 方法。
如果你想重新打开一个已经关闭的表单,你需要按照你最初创建的方式重新创建它:
YourFormType Mainmenu=new YourFormType();
Mainmenu.Show();
我假设您有一个主窗体,它创建了一个非模态子窗体。由于此子窗体可以独立于主窗体关闭,因此您可以有两种情况:
FormClosed
基本上,您的主窗体应该通过处理其事件来跟踪子窗体的生命周期:
class MainForm : Form
{
private ChildForm _childForm;
private void CreateOrShow()
{
// if the form is not closed, show it
if (_childForm == null)
{
_childForm = new ChildForm();
// attach the handler
_childForm.FormClosed += ChildFormClosed;
}
// show it
_childForm.Show();
}
// when the form closes, detach the handler and clear the field
void ChildFormClosed(object sender, FormClosedEventArgs args)
{
// detach the handler
_childForm.FormClosed -= ChildFormClosed;
// let GC collect it (and this way we can tell if it's closed)
_childForm = null;
}
}
上面智能呈现的代码的小补充
private void CreateOrShow()
{
// if the form is not closed, show it
if (_childForm == null || _childFom.IsDisposed )
{
_childForm = new ChildForm();
// attach the handler
_childForm.FormClosed += ChildFormClosed;
}
// show it
_childForm.Show();
}
// when the form closes, detach the handler and clear the field
void ChildFormClosed(object sender, FormClosedEventArgs args)
{
// detach the handler
_childForm.FormClosed -= ChildFormClosed;
// let GC collect it (and this way we can tell if it's closed)
_childForm = null;
}
您不能显示已关闭的表单。您可以调用 this.Hide() 来关闭表单。稍后您可以调用 form.Show();
要么,要么您需要重新创建表单。