![](/img/trans.png)
[英]How to close child forms running in their own threads when parent form closes? (non MDI)
[英]How to stop timer event when child form closes in MDI project
對於Windows窗體而言,我不是常規的,但在C#中一般都會越來越好。 我正在為一個comp開發一個項目。 PROG。 class,它是一個允許多個子表單的MDI表單。
這是我的泡菜,我在父表上有一個計時器; 勾選時,處理兩個標簽方法..一個用於計算文本文檔中的字符,另一個用於顯示縮放級別。
當孩子的窗戶打開時,我可以讓計時器觸發並處理我的事件,但是當我關閉窗口時,我試圖弄清楚如何停止計時器。 我已經嘗試了form.closing事件,並嘗試在我完成時禁用計時器,但這沒有幫助。
該項目是文本編輯器,對象的名稱為“文檔”。 當對象處於Disposed狀態時,我自然會得到一個異常,但我想在此之前禁用計時器。
“無法訪問已處置的對象”
這是我調用子表單實例的New()方法..
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();
}
你可以添加
TextEditorChild.FormClosing += new FormClosingEventHandler(Close);
在方法new()中
private void Close(object sender, FormClosingEventArgs e)
{
timer.Enabled = false;
}
並在下面添加,作為一種新方法
這使得當表單關閉時,它會停止計時器,然后退出表單
在您啟用計時器的行之前添加以下代碼:
var tec = TextEditorChild;
FormClosingEventHandler closing = null;
closing = (s, e) =>
{
tec.FormClosing -= closing;
if (--count == 0)
{
timer.Enabled = false;
}
};
tec.FormClosing += closing;
這應該在所有窗戶關閉時停止計時器。 我將模塊級TextEditorChild
捕獲為tec
,以確保在打開新的子窗口時引用不會更改。
我假設您在其他位置遞減count
數值,因此您需要調整邏輯以使其工作,但這應該是一個良好的開端。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.