2011-05-23 151 views
5

在我的C#應用​​程序中,當主窗體關閉時,我調用以下方法。子窗體關閉時父窗體關閉

private void FormMain_Closing(object sender, FormClosingEventArgs e) 
{ 
     // Show this dialog when the user tries to close the main form 
     Form testForm = new FormTest(); 
     testForm.StartPosition = FormStartPosition.CenterParent; 
     testForm.ShowDialog(); 
} 

這會創建一個對話框窗口,顯示主窗體何時關閉。但是,我的問題是,當用戶關閉testForm時,主表單會立即關閉。我已經嘗試過各種各樣的e.Cancel = true;等變體,並且仍然無法取消主窗體關閉。

任何想法?


編輯:它看起來像我遇到連續使用兩個ShowModal()的一個問題。展望這個問題...


編輯:使用this.DialogResult = DialogResult.None;它似乎已經解決了我的問題。從模態對話框打開模態對話框時,顯然是WinForms中的一個已知問題。

+1

我建議你把你的解決方案放在你的問題的答案中,並將其標記爲正確的答案。通過這種方式,其他人就會知道這個問題已經得到了回答 - 同時也看到您爲解決問題所做的一切。 – Mel 2011-05-23 01:25:39

回答

2

此代碼適用於我。我認爲你的代碼的另一部分存在問題。

private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    Form testForm = new FormTest(); 
    testForm.StartPosition = FormStartPosition.CenterParent; 
    testForm.ShowDialog(); 

    e.Cancel = testForm.DialogResult == DialogResult.Cancel; 
} 
1

這可以由孩子們太從docs處理:

如果一個表單有任何兒童或擁有 形式,一個事件的FormClosing也 提出的每一個。如果任何一個 表單取消該事件,則不會關閉任何 表單。因此,相應的FormClosed事件 是 不發送到任何窗體。

1

我知道你在你的問題中提到你曾嘗試使用'e.Cancel = true'但是,下面的代碼工作在我的環境(.NET 4.0,Visual Studio 2010中,Windows 7中):

private void Form1_FormClosing(object sender, FormClosingEventArgs e) { 
    // Show this dialog when the user tries to close the main form 
    Form testForm = new FormTest(); 
    testForm.StartPosition = FormStartPosition.CenterParent; 
    testForm.ShowDialog(); 
    e.Cancel = true; 
} 

如果你的情況不工作,你可以在工作中有其他的事件處理程序。在這種情況下,請在新生成的Windows窗體應用程序中嘗試此代碼。

+0

此外,.NET 4.6,VS 2015,Win 7(經過將近6年後,您將得到一個投票:)注意,您需要跟蹤任何已打開的子表單的結果[s]。 – 2017-03-08 20:08:07