[Yugong Series] Detailed Explanation of Label Controls on Winform Controls in August 2023


foreword

Winform controls are user interface elements in Windows Forms. They can be used to create various visual and interactive components of Windows applications, such as buttons, labels, text boxes, drop-down list boxes, check boxes, radio boxes, progress bars, etc. . Developers can use Winform controls to build user interfaces and respond to user actions to create powerful desktop applications.

1. Detailed explanation of Label control

Label control is one of the most commonly used controls in Windows Forms to display text or images.

Using the Label control in Visual Studio is very simple. You can add it by dragging and dropping a Label control to the form, or you can create it at runtime with the following code:

Label myLabel = new Label();
myLabel.Text = "Hello World!";
myLabel.Location = new Point(10, 10); // 设置Label控件在窗体中的位置
this.Controls.Add(myLabel); // 将Label控件添加到窗体中

1. Attribute introduction

The following explains several necessary and interesting attributes, and similar attributes will not be introduced in subsequent special articles.

1.1 AllowDrop

AllowDrop is a property commonly used in Winforms, which allows drag and drop operations on the control.

After setting AllowDrop to true, the control has the ability to support dragging. At this point we need to handle three events for the control:

  1. DragEnter: Triggered when the drag enters the control area, you can set the drag effect in this event.

  2. DragOver: Triggered when the drag is moving on the control, you can set the drag effect in this event.

  3. DragDrop: Triggered when the drag object is released in the control area, the drag and drop operation can be handled in this event.

Here is a simple example that drags and drops a file into a TextBox to display the file path:

  1. Set the AllowDrop property of the TextBox to true.

  2. Add DragEnter event response function for TextBox:

private void textBox1_DragEnter(object sender, DragEventArgs e)
{
    
    
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
    
    
        e.Effect = DragDropEffects.Copy;
    }
    else
    {
    
    
        e.Effect = DragDropEffects.None;
    }
}
  1. Add DragDrop event response function for TextBox:
private void textBox1_DragDrop(object sender, DragEventArgs e)
{
    
    
    string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
    textBox1.Text = files[0]; //显示文件路径
}

In this way, when we drag the file to the TextBox, the file path will be displayed automatically.

insert image description here

1.2 Anchor

Anchor is a very commonly used layout control property in Winform. It is used to control the position and size of the control to change adaptively as its parent container changes. Anchor has four values: Top, Bottom, Left, and Right, respectively representing the distance between the top, bottom, left, and right edges of the control and the corresponding edges of the parent container.

When using Anchor, you need to set the Anchor property of the control to the value of the edge that needs to be changed. For example, if you want the left side of the control to be fixed from the left side of the parent container and the right side to be adaptively changed from the right side of the parent container, then you need to set the control's The Anchor property is set to Left | Right.

Sample code:

//创建一个Label控件
Label lbl = new Label();
lbl.Text = "测试Label";
lbl.AutoSize = true;
lbl.Anchor = AnchorStyles.Left | AnchorStyles.Right;

//将控件添加到Form中
this.Controls.Add(lbl);

In the above code, we create a Label control, set its text to "Test Label", and set its adaptive parent container width. Then add it to the Form, as shown below:

insert image description here

When we change the window size, the width of the Label control will also change, but its distance from the left side of the window remains unchanged. This is what the Anchor property does.

1.3 AutoEllipsis

AutoEllipsis is a property in Winform, which is used to automatically add an ellipsis when a part of the text of the control exceeds the display area.

When designing a form, select the control that needs to add the AutoEllipsis property, such as Label or Button. Find the AutoEllipsis property in the properties window and set it to True.

When the text exceeds the display area of ​​the control, the control will automatically add ellipses. You can adjust the position and display effect of the ellipsis by modifying the size, font size, and text content of the control.

It should be noted that AutoEllipsis will only take effect when the control's AutoSize property is set to False. If the control's AutoSize property is set to True, the text will not exceed the display area, so the ellipsis will not appear.

The following is a sample code showing how to use the AutoEllipsis property in a Label control:

label1.Text = "这是一段很长很长的文本,它将会超出Label控件的显示区域,使用AutoEllipsis可以自动添加省略号。";
label1.AutoSize = false;
label1.AutoEllipsis = true;

insert image description here

1.4 autosize

The AutoSize property in Winform is a Boolean value that controls whether the size of the control adapts to its content.

When the AutoSize property is set to True, the control will automatically resize according to its content. For example, when you display long text in a Label control, it will automatically expand to fit the text.

The AutoSize property is often used in conjunction with the Dock and Anchor properties so that a control can be automatically sized and positioned according to its parent control.

At design time, you can set the AutoSize property by right-clicking on the control and selecting the "AutoSize" option. You can also set it in code like this:

label1.AutoSize = true; //设置AutoSize属性为true

You can set the AutoSize property dynamically while the program is running, such as resizing the form according to its content when the form loads:

private void Form1_Load(object sender, EventArgs e)
{
    
    
   label1.AutoSize = true;
   button1.AutoSize = true;
   //其他控件的AutoSize属性设置
}

insert image description here

Note: The AutoSize property only affects the size of the control, not its position. If you need more precise control over the position of the control, use the Anchor property or the Dock property.

1.5 backcolor

In Winform, the backcolor property is used to set the background color of the control. Can be set to a predefined color value or a custom color value.

Example of usage:

this.BackColor = Color.Yellow;

//创建一个Label控件
Label lbl = new Label();
lbl.Text = "这是一段很长很长的文本,它将会超出Label控件的显示区域,使用AutoEllipsis可以自动添加省略号。";
lbl.AutoSize = true;
lbl.AutoEllipsis = true;

//设置创建一个Label控件背景色为蓝色
lbl.BackColor = Color.Blue;

//设置创建一个Label控件自定义颜色背景色
lbl.BackColor = Color.FromArgb(255, 204, 102);

//将控件添加到Form中
this.Controls.Add(lbl);

In actual use, the backcolor attribute can be used together with other attributes to set the appearance of the control, such as setting the font color, border color, etc. of the control.
insert image description here

1.6 borderstyle

The Borderstyle property in Winform is used to set the border style of the control, including three types: None, FixedSingle, Fixed3D.

  • None: No border, the control does not display a border
  • FixedSingle: Single-line border, one line is displayed on the top, bottom, left and right sides of the control
  • Fixed3D: Three-dimensional border, a raised or sunken line is displayed on the top, bottom, left and right sides of the control

Instructions:

1. In the design mode, select the control that needs to set the borderstyle, find the Borderstyle property in the Properties window, and select the desired border style.

2. Set the borderstyle property in the code:

this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None; //设置为无边框
this.textBox2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; //设置为无边框
this.textBox3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; //设置为无边框

insert image description here

Note that not all controls support all border styles. For example, the Label control only supports the None and FixedSingle styles.

1.7 CausesValidation

In Winform, CausesValidation is a Boolean property used to determine whether the control will raise validation events. When this property is set to true, the control will raise validation events when it loses focus. When this property is set to false, the control does not raise validation events.

The steps to use the CausesValidation property are as follows:

  1. At design time, select the control whose CausesValidation property needs to be set.

  2. Find the CausesValidation property in the properties window and set it to true or false.

  3. If you set the CausesValidation property to true, you also need to bind validation events for the control.

The sample code is as follows:

textBox1.CausesValidation = true;
textBox1.Validating += new System.ComponentModel.CancelEventHandler(textBox1_Validating);

private void textBox1_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
    
    
    if (textBox1.Text == "")
    {
    
    
        MessageBox.Show("文本框不能为空!");
        e.Cancel = true; // 阻止焦点离开控件
    }
}

In the above example, when textBox1 loses focus, the textBox1_Validating validation event will be triggered. In this event, determine whether the text box is empty, if it is empty, a prompt box will pop up and prevent the focus from leaving the control. This way, the user has to enter a valid value to leave the textbox.

1.8 contextMenuStrip

ContextMenuStrip is a pop-up menu control in Winform, usually used in scenarios such as right-click menus. Here are the steps to use ContextMenuStrip:

  1. On the design interface, drag a ContextMenuStrip control from the toolbox to the form.

  2. Add a menu item in the properties window. In the Items property, you can add menu items by right-clicking or manually.

  3. Write code in the MouseDown event of the control that needs to display the ContextMenuStrip (such as Button, DataGridView, etc.), and display the ContextMenuStrip through the Show method. For example:

private void button1_MouseDown(object sender, MouseEventArgs e)
{
    
    
    if (e.Button == MouseButtons.Right)
    {
    
    
        contextMenuStrip1.Show(button1, e.Location);
    }
}
  1. Write the corresponding processing code in the Click event of the menu item in ContextMenuStrip.

  2. You can use the VisibleChanged event of ContextMenuStrip to realize the logic of performing certain operations when the menu is closed.

For example, here is a simple sample code:

private void button1_MouseDown(object sender, MouseEventArgs e)
{
    
    
    if (e.Button == MouseButtons.Right)
    {
    
    
        contextMenuStrip1.Show(button1, e.Location);
    }
}

private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
    
    
    MessageBox.Show("点击了菜单项1");
}

private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
    
    
    MessageBox.Show("点击了菜单项2");
}

private void contextMenuStrip1_VisibleChanged(object sender, EventArgs e)
{
    
    
    if (!contextMenuStrip1.Visible)
    {
    
    
        MessageBox.Show("菜单已关闭");
    }
}

insert image description here

1.9 Cursor

In Winform, you can use the Cursor class to control the appearance of the mouse cursor. The Cursor class has many predefined cursor types, such as arrows, hands, cursors, and so on. In addition, custom cursors can also be used.

The following are some commonly used methods and properties of the Cursor class:

  1. Current: Get or set the current cursor.
  2. Clip: Get or set the rectangular range of the cursor.
  3. Position: Get or set the coordinates of the cursor.
  4. Hide(): Hide the mouse cursor.
  5. Show(): Display the mouse cursor.
  6. SystemColors: Get the color of the system color cursor.

Here is some sample code:

// 设置光标
Cursor.Current = Cursors.WaitCursor;

// 隐藏光标
Cursor.Hide();

// 显示光标
Cursor.Show();

// 获取当前光标的坐标
Point p = Cursor.Position;

// 自定义光标
Cursor customCursor = new Cursor("customCursor.cur");
this.Cursor = customCursor;

It should be noted that when the cursor needs to be changed, the Control.Cursor property needs to be used. For example, to change the cursor in a form:

// 更改窗体光标
this.Cursor = Cursors.Hand;

insert image description here

1.10 Dock

In Winforms, the Dock property is used to set how a control is docked relative to its container. Specifically, the Dock property can be set to four values: Top, Bottom, Left, and Right, respectively indicating that the control is docked at the top, bottom, left, and right of the container.

For example, if you set the Dock property of a Label control to Top, the control will be docked at the top of its container, and when the size of the container changes, the control will automatically adjust its size and position to keep it docked at the top. The position is unchanged.

In addition, if there are multiple controls in a container, and their Dock properties are set differently, the positions of these controls in the container will change according to the setting of the Dock property.

It should be noted that when the Dock properties of multiple controls are set the same, their position order will be determined according to the order in which they are added in the container. If you need to change their order, you can do so by removing and re-adding the controls in the container.

Sample code:

Label label1 = new Label();
label1.Dock = DockStyle.Top;
label1.Text = "This is a label at the top of the container.";
label1.BackColor = Color.Blue;

Label label2 = new Label();
label2.Dock = DockStyle.Bottom;
label2.Text = "This is a label at the bottom of the container.";
label2.BackColor = Color.Yellow;

Label label3 = new Label();
label3.Dock = DockStyle.Left;
label3.Text = "This is a label at the left of the container.";
label3.BackColor = Color.Pink;

Label label4 = new Label();
label4.Dock = DockStyle.Right;
label4.Text = "This is a label at the right of the container.";
label4.BackColor = Color.SlateBlue;

this.Controls.Add(label1);
this.Controls.Add(label2);
this.Controls.Add(label3);
this.Controls.Add(label4);

This code creates a Panel container, adds four Label controls to the container, and sets their Dock properties. Finally, add the container to the Form form. After running the program, you can see that the four Label controls are respectively docked at the top, bottom, left and right of the Panel container.
insert image description here

Remember when AutoSize is true

2. Common scenarios

The common scenarios of Label control in Winform are:

  1. Display text: Label control can be used to display text information, such as window title, prompt information, author information, etc.

  2. Tab page: The Label control can be used as a tab page in a tab to display the name of the tab.

  3. Title: The Label control can be used as the title of the window or panel.

  4. Form: The Label control can be used as the label of each item in the form to display the name of each item.

  5. Status bar: The Label control can be used to display status bar information, such as operation completion prompts, progress bar percentage information, and so on.

  6. Hyperlink: The Label control can simulate a hyperlink, so that users can jump to other interfaces or open other files by clicking the label.

3. Specific cases

The Label control is one of the commonly used controls in Winform, and it is usually used to display text or images. The following is a specific case to illustrate how to use the Label control in Winform:

  1. Create a new Winform project in Visual Studio.
  2. Add a Label control to the Form.
  3. Right-click the Label control, select the "Properties" window, and enter the text to be displayed in the "Text" property, such as "Hello World".
  4. You can further set properties such as the font, color, size, and alignment of the Label control.
  5. Run the program, and the Label control will be displayed in the form.

For example, the following code demonstrates how to create a Label control in code and set its properties:

Label label1 = new Label();
label1.Text = "Hello World";
label1.Font = new Font("Arial", 12, FontStyle.Bold);
label1.ForeColor = Color.Blue;
label1.AutoSize = true;
label1.TextAlign = ContentAlignment.MiddleCenter;
this.Controls.Add(label1);

This code creates a Label control named label1, sets its text to "Hello World", font to Arial, size to 12, bold, color to blue, automatically resized to fit the text content, and centered. Finally, add the control to the current form.

insert image description here

Guess you like

Origin blog.csdn.net/aa2528877987/article/details/132582820