I converted this app from VB6. I have 2 forms. Form1 instantiates Form2 via a Menu Item. I am having trouble getting Form2 to end when clicking close (X). If Form2 is 'idle' it closes fine; but if 开发者_运维百科I am in a loop processing anything all the events fire, but it continues processing in Form2. I've tried messing with Dispose, Close, Application.Exit, Application.ExitThread. My last attempt was creating my own event to fire back to Form1 and dispose Form2 -- and it hits it but Form2 is still running. What is the deal? BTW if I use just Show vs ShowDialog -- Form2 just blinks and disappears.
Form1 does this
Dim f2 as Import
:
Hide()
f2 = New Import
AddHandler f2.die, AddressOf killf2
f2.ShowDialog(Me)
Show()
Private Sub killf2()
f2.Dispose()
f2 = Nothing
End Sub
Form2
Public Event die()
Private Shadows Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
Dispose()
Close()
e.Cancel = False
RaiseEvent die()
End Sub
I think you've got your events crossed. You want form1, containing an instance of form2, to listen for form2's form_closing event. Then you can set f2 = nothing.
Form1 should fully enclose form2.
here's an example:
Public Class MDIMain
Private WithEvents _child As frmViewChild
Friend Sub viewChildShow()
_child = New frmViewChild
_child.MdiParent = Me
_child.WindowState = FormWindowState.Maximized
_child.Show()
End Sub
Private Sub _child_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles _child.FormClosing
_child = Nothing
End Sub
don't add anything to form2, try
Dim f2 as Import
Hide()
f2 = New Import
f2.ShowDialog(Me)
Show()
Private Sub f2_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles f2.FormClosing
set f2 = nothing
End Sub
re: your comment it goes back to form2 and continues processing the next statement in the the click event handler
that's a feature and it will cause this behavior. you need to make sure me.close or close me is the last statement in form2, that there's nothing else to execute.
What is this loop you speak of? The user interface (windows) is separate from any code that is running. In your class derived form Form, Code is allowed to run, both before the Form is created, and after the Form is destroyed. If the code tries to access user-interface objects then an exception might occur, but otherwise there is nothing stopping your code from running when there is no user interface.
If you want your "for" loop to exit then you must send it a signal somehow, e.g. by creating a boolean "quit" member variable. Set "quit=True" when your form closes, then have your "for" loop check whether it is true.
精彩评论