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

我怎样才能再次打开它?

有帮助吗?

解决方案

当。。。的时候 Close 方法被调用 Form 你不能打电话给 Show 使表单可见的方法,因为表单的资源已经被释放了 Disposed. 。要隐藏窗体然后使其可见,请使用 Control.Hide 方法。

来自 MSDN

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

YourFormType Mainmenu=new YourFormType();
Mainmenu.Show();

其他提示

我认为您有一个主要表单,它会创建一个非模态子表单。由于此子表单可以独立于主要关闭,因此您可以有两种情况:

  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;
        }
    }
    
    .

您无法显示封闭形式。 您可以调用它。()关闭表单。 稍后您可以调用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;
}
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top