Search code examples
vb.netformsprogram-entry-point

How to add a form in the main function (Visual Basic)


I am trying to make a simple application in VB using main function , to show a form with a text label on it. I can do it using a form and adding label control to it, but for my project, I need to do it using main. It's like I want to write code for the whole application. My teacher said not to use graphical interface to develop. Please help.

Here is my code. It shows an empty form, no label. Please tell me how to add controls in the main function.

    Module Module1
    Sub Main()
        Dim f As New Form
        Application.Run(New Form1())
        Dim z As Label
        z = New Windows.Forms.Label
        Form1.Controls.Add(z)
        z.Text = "Hello"
        z.Show()
    End Sub
End Module

Solution

  • You are close with your attempt, but a few key parts are missing/out of order.

    I modified your code and added some comments to help get you started.

    Module Module1
        Sub Main()
            ' Create a new form object, but don't display it yet.
            Dim f As New Form
    
            ' Create a new Label.
            ' It will not be added to the form automatically.
            Dim z As New Label
            z.Text = "Hello"
            ' Now add the label to the form.
            f.Controls.Add(z)
    
            ' Open the form and wait until the user closes it before continuing.
            f.ShowDialog()
        End Sub
    End Module
    

    One thing you might want to consider is wrapping the form (f) in a Using block which is a good practice to get into since it will automatically handle proper disposal of the object. If you do this, your code now looks like:

    Module Module1
        Sub Main()
            ' Create a new form object, but don't display it yet.
            Using f As New Form
    
                ' Create a new Label.
                ' It will not be added to the form automatically.
                Dim z As New Label
                z.Text = "Hello"
                ' Now add the label to the form.
                f.Controls.Add(z)
    
                ' Open the form and wait until the user closes it before continuing.
                f.ShowDialog()
    
            End Using ' Now all the "garbage" of Form f is cleaned up.
    
        End Sub
    End Module