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

时间:2015-01-02 17:11:56

标签: vb.net forms main

我正在尝试使用main函数在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

3 个答案:

答案 0 :(得分:1)

您需要将标签添加到“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

答案 1 :(得分:1)

除非您知道它的用途,否则不应使用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)

答案 2 :(得分:1)

您的尝试已接近尾声,但有几个关键部分缺失/无序。

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

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