Search code examples
vb.netwinformsstartup

Programmatically change the startup form on application launch?


Can I programmatically change the startup form on application launch in VB.Net?


Solution

  • Sure you can!

    In your Project Properties, set Startup Object to Sub Main, and make sure that there's a Public Sub Main method somewhere in your application. A separate startup class may be a good idea:

    Public Class myStartupClass

    ''' <summary>
    ''' This is the method that will be run when the application loads, 
    ''' because Project Properties, Startup Object is set to SubMain
    ''' </summary>
    ''' <remarks>
    ''' </remarks>
    ''' --------------------------------------------------------------------------------
    Public Shared Sub Main()
    
        'The form that we will end up showing
        Dim formToShow As System.Windows.Forms.Form = Nothing
    
        'The determiner as to which form to show
        Dim myMood As String = "Happy"
    
        'Choose the appropriate form
        Select Case myMood
            Case "Happy"
                formToShow = New Form1
            Case Else
                formToShow = New Form2
        End Select
    
        'Show the form, and keep it open until it's explicitly closed.
        formToShow.ShowDialog()
    
    End Sub
    

    End Class