Villager A
Villager A

Reputation: 39

VB.NET End application in Form2

Here's my scenario:

I have two forms named Form1 and Form2.
Form1 has a button.
When the button is pressed, Form1 will become hidden and Form2 will be shown.
If I close Form2 by pressing [x] button on the top right of the form, the application is still running.
According what I get in my research, it seems I have to work with FormClosingEventArgs.
Anyone have any idea?

Upvotes: 1

Views: 1427

Answers (3)

Shell
Shell

Reputation: 6849

Seems you are not closing your first form. You are just hiding the first form instead of closing it. You should also close the first form. But, if you are creating an object of Form2 in Form1 then you can't close the first form. if you close it then the Form2 will not be displayed because the object of Form2 will be disposed initially. So, you should handle the FormClosed event of Form2 in Form1 when the Form2 is being displayed.

'Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Me.Hide()
    Dim form As New Form2
    AddHandler form.FormClosed, AddressOf Me.form2_FormClosed
    form.Show()
End Sub
Private Sub form2_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs)
    Me.Close()
End Sub

Upvotes: 0

MOB
MOB

Reputation: 195

Find Shutdown Mode in your application properties. There you will see two options. 1. When start up form closes. 2. When last form closes.

If you choose no.1 then until you close your start up form your application will not close but you can apply force close. eg.

    Private Sub Form2Closing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
    End
End Sub

And if no.2 then your application will close automatically when last active form closes.

Hope this is ok

Upvotes: 2

Villager A
Villager A

Reputation: 39

Problem solved.

Private Sub Form2Closing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
    Form1.Close()
End Sub

Please give more suggestion to me if there is another nice way :)

Upvotes: -1

Related Questions