2014-01-25 45 views
0

對於Windows窗體,我不是經常性的,但通常在C#中會變得更好。我正在開發一個comp的項目。 PROG。類,它是一個允許多個子窗體的MDI表單。如何在MDI項目中關閉子窗體時停止計時器事件

這是我的泡菜, 我在父母的窗體上有一個計時器;當勾選時,處理兩個標籤方法..一個用於計算文本文檔中的字符,另一個用於顯示縮放級別。

我可以讓計時器觸發和處理我的事件,當一個孩子的窗戶打開,但當我關閉窗口,我想弄清楚如何停止計時器一些如何。 我已經嘗試了form.closing事件,並嘗試禁用計時器,當我完成,但這並沒有幫助。

該項目是一個文本編輯器和對象的名稱ID「文檔」。當對象被處置時,自然我會得到一個異常,但是我想在這種情況發生之前禁用定時器。

「無法訪問已釋放的對象」

這是我的新()方法調用子窗體的一個實例..

 void New() 
     { 
      // Generate a new form from scratch 
      TextEditorChild = new Form(); // Declare a variable containing a new Form method 
      TextEditorChild.Text = "Document " + count.ToString(); // Text Property - also gets the forms order number 
      TextEditorChild.Icon = Properties.Resources._new_doc_icon; // Use our own icon 
      TextEditorChild.MdiParent = this; // Ensure we are using the original form as the parent form 
      Document = new RichTextBox(); // Call a new RichTextBox object 
      Document.Multiline = true; // Yes, a multiline textbox 
      Document.Dock = DockStyle.Fill; // Ensure that the textbox fills the new window 
      TextEditorChild.Controls.Add(Document); // Apply our controls to the child window 
      TextEditorChild.Show(); // Display the window 
      count++; // Add this window to a potnetial list of windows, should multiple be opened all at once 
      timer.Enabled = true; 
     } 

這裏是我的計時器,甚至處理...

 private void timer_Tick(object sender, EventArgs e) 
    { 
      charCount.Text = "Characters in the current document: " + Document.TextLength.ToString(); 
      zoom.Text = Document.ZoomFactor.ToString(); 
    } 
+0

你打開了多個TextEditorChild還是隻打開一個? – Steve

+0

它只拋出一個異常。 實際上,我發佈的代碼不會允許定時器開始。 我的第一個刺是創建和IF語句和 ' if(TextEditorChild == null) { return; } 其他 {// 方法 } ' 這個工作,但是當我關閉子窗口,我再次得到了消息。 –

回答

1

您可以添加

TextEditorChild.FormClosing += new FormClosingEventHandler(Close); 

在該方法中的新()


private void Close(object sender, FormClosingEventArgs e) 
{ 
    timer.Enabled = false; 
} 

並添加此以下,作爲一種新的方法


這使得使得當窗體關閉時,停止計時器,並然後退出表格

+0

明白了。 我可能已經嘗試過類似的東西,但我不確定在方法中使用什麼類型的參數。 謝謝! –

+0

很高興我可以幫助:) – Joe

1

就在您啓用計時器的行之前添加此代碼:

 var tec = TextEditorChild; 
     FormClosingEventHandler closing = null; 
     closing = (s, e) => 
     { 
      tec.FormClosing -= closing; 
      if (--count == 0) 
      { 
       timer.Enabled = false; 
      } 
     }; 
     tec.FormClosing += closing; 

這應該會在所有窗口關閉時停止計時器。我將模塊級別TextEditorChild捕獲爲tec以確保在您打開新的子窗口時引用不會更改。

我假設你正在遞減其他地方的count值,所以你需要調整你的邏輯來完成這個工作,但這應該是一個好的開始。

+0

我無法得到該方法的工作。 雖然我喜歡用它,但我有一個類似的想法,只是當我的子窗口數減少到零時禁用計時器。 –

+0

我會繼續以不同的方式嘗試這種方法,因爲這對我來說也是一個理想的處理方式。 我也很欣賞你的意見。 –

+0

@ codeman061988 - 什麼沒有工作? – Enigmativity

相關問題