【发布时间】:2012-03-10 07:58:29
【问题描述】:
我想知道如何使用 this.Close() 再次打开已关闭的表单。每次我尝试使用 Mainmenu.Show() 打开关闭的表单时,异常都会引发错误“无法访问已处置的对象。对象名称:Mainmenu”。
我怎样才能再次打开它?
【问题讨论】:
标签: c# forms show objectdisposedexception
我想知道如何使用 this.Close() 再次打开已关闭的表单。每次我尝试使用 Mainmenu.Show() 打开关闭的表单时,异常都会引发错误“无法访问已处置的对象。对象名称:Mainmenu”。
我怎样才能再次打开它?
【问题讨论】:
标签: c# forms show objectdisposedexception
当在Form 上调用Close 方法时,您不能调用Show 方法来使表单可见,因为表单的资源已经被释放,即Disposed。要隐藏表单并使其可见,请使用 Control.Hide 方法。
如果你想重新打开一个已经关闭的表单,你需要按照你最初创建的方式重新创建它:
YourFormType Mainmenu=new YourFormType();
Mainmenu.Show();
【讨论】:
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;
}
}
【讨论】:
您不能显示已关闭的表单。 您可以调用 this.Hide() 来关闭表单。 稍后你可以调用 form.Show();
要么这样,要么您需要重新创建表单。
【讨论】:
上面智能呈现代码的小补充
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;
}
【讨论】: