Vb.net 如何使二级子窗体在关闭时提示?

Vb.net 如何使二级子窗体在关闭时提示?,vb.net,winforms,Vb.net,Winforms,问题:对话框的FormClosing()事件如果是子窗体,即其所有者属性设置为父窗体,但如果是子窗体的子窗体,则不会引发。因此,关闭主窗体不会在任何子对话框上调用关闭事件 详细信息:在FormClosing()事件中,一个对话框提示“保存更改”,并带有YesNoCancel按钮。单击“取消”将保持对话框打开(即取消关闭) Private Sub Dialog_FormClosing(...) Handles Me.FormClosing If MessageBox.Show("Save

问题:对话框的FormClosing()事件如果是子窗体,即其所有者属性设置为父窗体,但如果是子窗体的子窗体,则不会引发。因此,关闭主窗体不会在任何子对话框上调用关闭事件

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

Private Sub Dialog_FormClosing(...) Handles Me.FormClosing
    If MessageBox.Show("Save Changes?", YesNoCancel) = No Then
        e.Cancel = True
    End If
End Sub
因此,实例化一个新对话框,并设置其所有者属性

// 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()事件

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


谢谢您的回复。

是的。部分问题在于,您将它们作为对话框进行讨论,但实际上没有使用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关闭。

是的。部分问题在于,您将它们作为对话框进行讨论,但实际上没有使用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关闭