如何在主函数中添加表单 (Visual Basic)

how to add form in main function (Visual Basic)

我正在尝试使用主要功能在 VB 中制作一个简单的应用程序,以显示一个表单并在其上添加一个文本标签。我可以使用表单并向其添加标签控件来完成它,但是对于我的项目我需要使用 main 来完成它......就像我想为整个应用程序编写代码一样,我的老师说不要使用图形界面来开发......请帮助

这是我的代码...它显示空表格,没有标签....请告诉我如何在主函数中添加控件......

    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

您需要将标签添加到 "f" 实例,而不是 Form1.Controls。

Module Module1
Sub Main()
    Dim f As New Form
    Dim z As Label
    z = New Windows.Forms.Label
    z.Text = "Hello"

    f.Controls.Add(z)        
    f.ShowDialog()

End Sub
End Module

你不应该使用 Application.Run 除非你知道它的作用,查看这个综合答案了解它的用途 Application.Run(Form) vs. Form.Show()?

试试这个,让您的表单在其中显示您的标签:

Module Module1
    Sub Main()
        Dim myForm as Form = New Form
        Dim myLabel As Label = New Windows.Forms.Label
        myLabel.Text = "Hello"
        myForm.Controls.Add(myLabel)

        myForm.Show()

    End Sub
End Module

您也可以随时以编程方式访问控件的所有设计属性,例如,也可以在将控件添加到窗体之前添加以定义标签控件的位置

myLabel.Location = New Point(20, 20)

您的尝试已接近尾声,但一些关键部分 missing/out 有问题。

我修改了您的代码并添加了一些注释以帮助您入门。

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

您可能要考虑的一件事是将表单 (f) 包装在 Using block 中,这是一个很好的做法,因为它会自动处理对象的正确处置。如果你这样做,你的代码现在看起来像:

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