Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open and closing forms on exit in visual basic?

How do you reload the main form on exit of a secondary form? For example, if frmMain is the main form and you hid that to load another form called GenerateNumbers, then how do you get frmMain back when the user exits GenerateNumbers?

like image 280
Brandon Avatar asked Apr 17 '26 09:04

Brandon


2 Answers

The best way is to add an an event handler to the child form's Closing event. That way, the main form will receive notification when the child form closes and then it can just re-show itself. For instance:

AddHandler frmChild.Closing, AddressOf ChildClosing
frmChild.Show()
Me.Hide()

'....

Private Sub ChildClosing(sender As Object, e As EventArgs)
    RemoveHandler CType(sender, Form).Closing, AddressOf ChildClosing
    Me.Show()
End Sub

As others have said, if you show the child form with the ShowDialog method, that's much easier. In fact, if you do that, then there's really no reason to hide the main form, you can just pass the main form into the dialog as the owner:

frmChild.ShowDialog(Me)

Hint: If you don't hide the main form, set the starting position property of the child form to center over the owner.

Alternatively, you could give a reference to the main form so that it can make the main form visible when it is closing, but I'd say that's the least desirable option.

like image 80
Steven Doggart Avatar answered Apr 20 '26 00:04

Steven Doggart


If you called the secondary Form with ShowDialog you would then make your Main Form Visible after the Secondary Form returned from the ShowDialog Method.

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim frm2 As Form2 = New Form2
    Me.Hide()
    frm2.ShowDialog()
    Me.Show()
End Sub
like image 28
Mark Hall Avatar answered Apr 19 '26 22:04

Mark Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!