将控件添加到窗体(Windows 窗体 .NET)

大多数窗体的设计方法如下:向窗体表面添加控件,以定义用户界面 (UI)。 控件是窗体上的组件,用于显示信息或接受用户输入

将控件添加到窗体的主要方法是使用 Visual Studio 设计器,但你也可以在运行时使用代码来管理窗体上的控件。

重要

面向 .NET 7 和 .NET 6 的桌面指南文档正在撰写中。

使用设计器添加

Visual Studio 使用窗体设计器设计窗体。 “控件”窗格列出了应用可使用的所有控件。 可以通过两种方式从窗格中添加控件:

通过双击添加控件

双击控件时,它将自动添加到当前打开的具有默认设置的窗体中。

Double-click a control in the toolbox on visual studio for .NET Windows Forms

通过拖动添加控件

通过单击选择控件。 在窗体中,拖选一个区域。 放置控件以适应所选区域的大小。

Drag-select and draw a control from the toolbox on visual studio for .NET Windows Forms

使用代码添加

可以创建控件,然后在运行时使用窗体的 Controls 集合将其添加到窗体。 还可以使用此集合将控件从窗体中删除。

以下代码添加并放置了两个控件,即 LabelTextBox

Label label1 = new Label()
{
    Text = "&First Name",
    Location = new Point(10, 10),
    TabIndex = 10
};

TextBox field1 = new TextBox()
{
    Location = new Point(label1.Location.X, label1.Bounds.Bottom + Padding.Top),
    TabIndex = 11
};

Controls.Add(label1);
Controls.Add(field1);
Dim label1 As New Label With {.Text = "&First Name",
                              .Location = New Point(10, 10),
                              .TabIndex = 10}

Dim field1 As New TextBox With {.Location = New Point(label1.Location.X,
                                                      label1.Bounds.Bottom + Padding.Top),
                                .TabIndex = 11}

Controls.Add(label1)
Controls.Add(field1)

另请参阅