Reputation: 3512
I have a question about closing and disposing a hidden child form.
Parent form with two buttons:
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
Child form:
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
As long as Form1 is open, I don't want to close Form2. So that part works.
But I do want to close Form2 when Form1 is closed. Do I have to close it explicitly from Form1? And add more logic to Form2_FormClosing()?
As is, Form2_Disposed() never gets called as far as I can tell (I never get the message box). Is this correct?
When Form1 is disposed, variable F2 no longer exists. Will the Form2 be disposed by the garbage collector later on or not?
Upvotes: 0
Views: 358
Reputation: 216293
I will try to move the Form2_FormClosing event to the Form1 class.
In this way you will be able to control the closing of the Form2 instance from the Form1 instance.
' 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
Please, pay attention that this is an example, you need to handle special cases like windows shutdown using the FormClosingEventArgs.CloseReason property
Upvotes: 1