VB Code:
Module Module1
Public mainForm As Form 'The current primary form.
Sub Main()
'Start the app with a new instance of Form1
mainForm = New Form1
'Keep showing the current main form until there isn't one.
Do
Application.Run(mainForm)
Loop While Not mainForm Is Nothing
End Sub
End Module
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Open a new main form and close this one.
mainForm = New Form2
Me.Close()
End Sub
Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
If mainForm Is Me Then
'This is the main form so let the app exit.
mainForm = Nothing
End If
End Sub
End Class
Public Class Form2
Private Sub Form2_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
If mainForm Is Me Then
'This is the main form so let the app exit.
mainForm = Nothing
End If
End Sub
End Class
Note that you cannot use this method to switch the main form to one that is already open because the call to Application.Run will try to display it. This will cause an exception to be thrown if the form is already displayed.