【问题标题】:Parent form closing when child form closes子窗体关闭时父窗体关闭
【发布时间】:2011-08-30 19:29:33
【问题描述】:

在我的 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 中的一个已知问题。

【问题讨论】:

  • 我建议您将您的解决方案放在answer 到您的question 中,并将其标记为正确答案。这样一来,其他人就会知道这个问题已经得到解答 - 并且还会看到您为解决问题所做的工作。

标签: c# forms event-handling


【解决方案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 窗体应用程序中尝试此代码。

【讨论】:

  • 另外,.NET 4.6,VS 2015,Win 7(将近 6 年后,您获得了赞成票 :) 请注意,您需要跟踪打开的任何子表单的结果。
【解决方案2】:

这也可以由docs 的孩子处理:

如果表单有任何子或拥有 表单,FormClosing 事件也是 为每一个提出。如果其中任何一个 形式取消事件,没有 表格已关闭。因此 相应的 FormClosed 事件是 未发送到任何表单。

【讨论】:

    【解决方案3】:

    此代码适用于我。我认为您的代码的另一部分存在问题。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多