处理隐藏的表格

时间:2012-05-29 19:55:23

标签: .net winforms garbage-collection parent-child

我对关闭和处理隐藏的子表单有疑问。

包含两个按钮的父表单:

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将在以后由垃圾收集器处理吗?

1 个答案:

答案 0 :(得分: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属性处理Windows关闭等特殊情况