【问题标题】:How can I make second-level child forms prompt on close?如何在关闭时提示二级子表单?
【发布时间】:2011-01-14 19:51:09
【问题描述】:

问题:如果对话框是子窗体,则会引发对话框的 FormClosing() 事件,即它的 Owner 属性设置为父窗体,但如果它是子窗体则不会。所以关闭主窗体不会调用任何孙子对话框的关闭事件。

详细信息:对话框提示“保存更改?”,在 FormClosing() 事件中带有 YesNoCancel 按钮。单击“取消”使对话框保持打开状态,即取消关闭。

Private Sub Dialog_FormClosing(...) Handles Me.FormClosing
    If MessageBox.Show("Save Changes?", YesNoCancel) = No Then
        e.Cancel = True
    End If
End Sub

因此实例化一个新对话框,并设置其 Owner 属性...

// called from the main form
Dim dlg As New Dialog
dlg.Owner = Me
dlg.Show()

... 的好处是,如果用户尝试关闭所有者/父级,对话框将提示保存。单击“取消”将使对话框保持打开状态,它的所有者也是如此。

但是,如果相同的对话框是从 父级的子级(也设置了它的所有者属性)而不是父级显示的:

// called from another child 
Dim dlg As New Dialog
dlg.Owner = Me
dlg.Show()

如果最上面的父级已关闭,则不会引发子级的 FormClosing() 事件。

这是框架中已知的设计限制吗?在我开始为此破解一个讨厌的解决方案之前,我应该考虑什么?

感谢您的任何回复。

【问题讨论】:

    标签: vb.net winforms


    【解决方案1】:

    是的。部分问题是您将它们视为对话框,但实际上并未使用 ShowDialog() 方法来显示它们。这将使用户无法在显示对话框时关闭主窗体。消息循环在主窗体关闭时终止,其余窗体将被丢弃,无需通过正常的关闭顺序。

    一种解决方案是在主窗体关闭时自己主动关闭窗体。这很好用:

      Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        For frm As Integer = Application.OpenForms.Count - 1 To 1 Step -1
          Application.OpenForms(frm).Close()
          If Application.OpenForms.Count - 1 = frm Then
            e.Cancel = True
            Exit For
          End If
        Next
      End Sub
    

    您可能应该注意 e.CloseReason,以免阻止 Windows 关机。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多