【问题标题】:Open the closed form打开封闭的表格
【发布时间】:2012-03-10 07:58:29
【问题描述】:

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

我怎样才能再次打开它?

【问题讨论】:

    标签: c# forms show objectdisposedexception


    【解决方案1】:

    当在Form 上调用Close 方法时,您不能调用Show 方法来使表单可见,因为表单的资源已经被释放,即Disposed。要隐藏表单并使其可见,请使用 Control.Hide 方法。

    from MSDN

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

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

    【讨论】:

    • 我的意图是关闭表单并重新打开它。那么如何打开已关闭的表单?
    • 如果你想重新打开一个已经关闭的表单,你需要重新创建它,就像你最初创建的一样:YourFormType Mainmenu=new YourFormType(); Mainmenu.Show()
    【解决方案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;
        }
    }
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

        • 感谢您提交,Azzam。请注意,通常首选编辑现有答案而不是添加新答案以进行小更新。
        • Brett Wolfington 谢谢你通知我,最好的问候
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-24
        相关资源
        最近更新 更多