2012-03-10 146 views
2

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

如何再次打开它?

回答

3

Close方法被调用在Form你不能调用Show方法使窗体可见,因为窗体的资源已被释放又名Disposed。要隐藏窗体并使其可见,请使用Control.Hide方法。

from MSDN

如果你想重新打开已关闭的形式,则需要再次重新创建它,你在第一次创建,它以同样的方式:

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

我的本意关闭表单并重新打开它。所以我怎样才能打开封闭的形式? – Sephiroth111 2012-03-10 08:09:25

+0

如果您想重新打开已关闭的表单,则需要按照您创建的相同方式重新创建它 - 首先:YourFormType Mainmenu = new YourFormType(); Mainmenu.Show()' – 2012-03-10 08:14:36

0

你不能显示一个封闭的表单。 你可以调用this.Hide()来关闭表单。以后你可以调用form.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; 
    } 
} 
+0

@downvoter:谨慎解释这个答案“没有用”? – Groo 2012-03-10 08:28:02

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

感谢您的提交,Azzam。请不要认为编辑现有的答案通常是首选,而不是为小的更新添加新的答案。 – 2014-10-04 18:00:11

+0

Brett Wolfington谢谢通知我,Best Regard – 2014-10-04 18:42:17