0

我有一个关于关闭和处理隐藏的子表单的问题。

带有两个按钮的父窗体:

Public Class Form1
    Dim F2 As Form2

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        F2 = New Form2
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        F2.Show()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        F2.Hide()
    End Sub
End Class

子表:

Public Class Form2
    Private Sub Form2_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
            e.Cancel = True
            Me.Hide()
    End Sub

    Private Sub Form2_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.VisibleChanged
        MsgBox("Form2.Visible = " & Me.Visible.ToString)
    End Sub

    Private Sub Form2_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
        MsgBox("Form2 has been disposed.")
    End Sub
End Class

只要 Form1 是打开的,我就不想关闭 Form2。所以那部分有效。
但是我确实想在 Form1 关闭时关闭 Form2。我是否必须从 Form1 显式关闭它?并为 Form2_FormClosing() 添加更多逻辑?
就我所知,Form2_Disposed() 永远不会被调用(我永远不会得到消息框)。它是否正确?
当 Form1 被释放时,变量 F2 不再存在。垃圾收集器稍后会处理 Form2 吗?

4

1 回答 1

1

我将尝试将 Form2_FormClosing 事件移至 Form1 类。
通过这种方式,您将能够从 Form1 实例控制 Form2 实例的关闭。

' global instance flag
Dim globalCloseFlag As Boolean = False

...
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load  
    F2 = New Form2  
    AddHandler F2.FormClosing, New FormClosingEventHandler(AddressOf Form2ClosingHandler)
End Sub  

' This will get the event inside the form1 instance, you can control the close of F2 from here
Private Sub Form2ClosingHandler(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) 
    if globalCloseFlag = false then    
        e.Cancel = True    
        F2.Hide()
    end if

End Sub 

' Form1 closing, call the close of F2
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing      
      globalCloseFlag = True
      F2.Close()
End Sub      

请注意,这是一个示例,您需要使用 FormClosingEventArgs.CloseReason 属性来处理窗口关闭等特殊情况

于 2012-05-29T20:16:09.187 回答