2

我想知道如何使用 this.Close() 再次打开关闭的表单。每次我尝试使用 Mainmenu.Show() 打开关闭的表单时,异常都会引发错误“无法访问已处置的对象。对象名称:Mainmenu”。

我怎样才能再次打开它?

4

4 回答 4

2

Close在 a上调​​用该方法时,Form您不能调用该Show方法使表单可见,因为表单的资源已经被释放 aka Disposed。若要隐藏窗体然后使其可见,请使用 Control.Hide 方法。

来自 MSDN

如果你想重新打开一个已经关闭的表单,你需要按照你最初创建的方式重新创建它:

YourFormType Mainmenu=new YourFormType();
Mainmenu.Show();
于 2012-03-10T08:01:44.413 回答
2

我假设您有一个主窗体,它创建了一个非模态子窗体。由于此子窗体可以独立于主窗体关闭,因此您可以有两种情况:

  1. 子窗体尚未创建,或已关闭。在这种情况下,创建表单并显示它。
  2. 子窗体已经在运行。在这种情况下,您只需要显示它(它可能会被最小化,并且您会想要恢复它)。

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;
    }
}
于 2012-03-10T08:23:37.570 回答
0

上面智能呈现的代码的小补充

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;
}
于 2014-10-04T17:29:59.627 回答
0

您不能显示已关闭的表单。您可以调用 this.Hide() 来关闭表单。稍后您可以调用 form.Show();

要么,要么您需要重新创建表单。

于 2012-03-10T08:14:27.570 回答