Search code examples
vb.netwinformstitlebar

vb.net close winforms application from title bar X button


Using VB.Net on a winforms application I have two forms
Both forms are set to "When Last Form Closes"
Both forms have "Key Preview" set to TRUE
frmOne the start up form has a "Form Border Style" set to FixedToolWindow
Here are the sequence of events preformed with the two forms
Load frmOne and click the X button on the title bar form closes and the start button shows up in the IDE
This is the desired behavior
Second sequence of events load app frmOne has a button to navigate to frmTwo and frmTwo has a button to navigate back to frmOne When we arrive back at frmOne we click the X button on the title bar and frmOne close but the app is still running NO Start button in the IDE

The Question is how to close the application after navigating to other forms?
The Code Below are the various ways I have tried to solve this issue
I am including the KeyPress Code which does not exhibit the desired results

    Private Sub frmOne_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Me.KeyPress
    'frmOne Property KeyPreview needs to be set to True
    If Asc(e.KeyChar) = 27 Then
        'MessageBox.Show("You Pressed " & e.KeyChar)
        Me.Close()
    End If
End Sub
'Public Sub frmOne_QueryClose(Cancel As Integer, CloseMode As Integer)
'Prevent user from closing with the Close box in the title bar.
'If CloseMode = 1 Then Me.Close()
'If CloseMode = 1 Then Application.Exit()
'End Sub

'Private Sub frmOne_FormClosing(sender As Object, e As FormClosingEventArgs) 'Handles Me.FormClosing
'Application.Exit()
'Me.Close()
'End Sub

Private Sub frmOne_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
    'Application.Exit()
End Sub

Code to frmTwo

   Private Sub btnToFormTwo_Click(sender As Object, e As EventArgs) Handles btnToFormTwo.Click
    Dim i As Integer
    i = txtBoxOne.Text.Length
    If i = 0 Then
        MsgBox("Enter Data")
        txtBoxOne.Select()
        Return
    End If
    Dim OBJ As New frmTwo
    OBJ.SPass = txtBoxOne.Text
    OBJ.Show()
    lblFormOne.Text = " "
    txtBoxOne.Clear()
    Me.Hide()

    'Me.Close()'R Click project PassVar Set Start Up Form
    'Best Solution is to have Splash Form as Start Up Form
End Sub

Code Back to frmOne

    Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
    frmOne.txtBoxOne.Text = "Back from 2"

    Me.Hide()
    frmOne.Show()
End Sub

Solution

  • You need to close Forms to get the application to end. I use "When last form closes" in a project with maybe a dozen forms and it works fine.

    Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
        frmOne.txtBoxOne.Text = "Back from 2"
    
        'Me.Hide() 'frmTwo is still running, To close a form use .Close()
        Close()
        frmOne.Show()
    End Sub