2012-03-10 143 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