This article is enough to learn Windows Forms (explanation of C# controls)

Table of contents

1. Form form

1.1 Creation and deletion of forms

1. Add a form

2. Delete the form

3. Use of multiple forms

1.2. Form properties

1.2.1 Change the form icon

1.2.2 Hide the title bar of the form (FormBorderStyle property)

1.2.3 Control the display position of the form (StartPosition property)

1.2.4 Setting of form background image

1.2.5 Showing and hiding forms

1.3 Form events

1.3.1 Click event (Click)

 1.3.2 Loading event (Load)

1.3.3 Closing event (FormClosing)

Supplement: Why is it shown that the window is still running when I close it the next time I start it?

 2. MDI form

 2.1 Set up MDI form

2.1.1 Set the parent form

2.1.2 Set up subform

2.2 Arrange MDI subforms

3. Form controls

1.1 Overview of controls

1.2 Related operations of controls

2.1 Text control

2.1.1Label control

2.1.2Button control

2.1.3TextBox control

2.1.4RichTextBox control

Hyperlink style

richTextBox text box settings

3.1 Select class controls

3.1.1ComboBox control

Adding elements: divided into manual and code addition.

Set drop-down style (DropDownStyle)

3.1.2CheckBox control

3.1.3RadioButton radio button

1. Determine whether the radio button is selected

2. Respond to the radio button selected state change event

3. Group radio buttons

3.1.4NumericUpDown control

1. Maximum value/minimum value setting

2. Get the value displayed in the NumericUpDown control

3. Set the display mode of numerical values ​​in the NumericUpDown control

3.1.5ListBox control

1. Add and remove items in the ListBox control

2. Create a list control that always displays scroll bars

3. Select multiple items in the ListBox control

4.1 Group controls

4.1.1Panel control

4.1.2GroupBox control

Edit

 4.1.3TabControl control

1. Tab picture display style

2. A prompt message will pop up when the mouse is moved into

Edit

3. Display the tab as a button style

 4. Add controls to the tab

5.1 Menu, toolbar and status bar controls

5.1.1MenuStrip control

5.1.2 Pop-up menu (ContextMenuStrip)

5.1.3ToolStrip control (toolbar)

5.1.4StatusStrip control (status bar)

6.1.1ImageList control (picture collection)

1. ImageList control code adds pictures

 2. Remove pictures through code in the ImageList control

7.1PictureBox control (picture display)

PictrueBox control displays pictures

8.1Timer control (timer)

1. Common properties, methods and events of Timer control

Edit Edit

 2. Timer implements time change

 9.1ListView control (option list with icons)

1. Add and remove items in the ListView control

1. Add items

2. Remove items

2. Select an item in the control by default

3. Add icons to the ListView control

 4. Enable tiled view in the control

5. Group items in the ListView control

 10.1TreeView control (tree node)

10.1.1TreeView common properties and events

10.1.2 Adding and deleting tree nodes

1. Add tree nodes

2. Remove nodes

10.1.3 Get the selected node in the TreeView control

10.1.4 Set icons for nodes in the TreeView control

11.1DateTimePicker control (date time box)

11.1.1 Use DateTimePicker control to display time

11.1.2 Display date in custom format

11.1.3 Get the date selected in the control

12.1MonthCalendar control (calendar control)

12.1.1MonthCalendar control displays the week number

12.1.2 Display multiple months in the MonthCalendar control

 12.1.3 Select date range in MonthCalendar control

13.1ErrorProvider control (validation of text box input)

1. Verify text box

 13.2HelpProvider control (calling help documentation)

13.3ProgressBar control (progress bar)


1. Form form

From form, also called window, is the smart client technology of .NET framework;

1.1 Creation and deletion of forms

1. Add a form

This form is created in Vs. You can right-click the project name---Add--Windows Form. Generally, project types are Windows Forms (.NET Framework)

2. Delete the form

Right-click on the corresponding form and delete it

3. Use of multiple forms

When Xiaobai first created multiple forms as shown in the figure, only one form was displayed when ctrl+F5 was run.

 Then we can click Program.cs and add it belowApplication.Run(new form name ()); to start other windows Body

1.2. Form properties

1.2.1 Change the form icon

Select the Icon property on the property panel to change the icon. Butthe image format needs to be ico.

1.2.2 Hide the title bar of the form (FormBorderStyle property)

FormBorderStyle properties and descriptions
attribute value illustrate attribute value illustrate
Fixed3D Fixed three-dimensional border None Rimless
FixedDialog Fixed dialog style Sizable Resizable borders
FixedSingle Fixed single line border SizableToolWindow Resizable tool window borders
FixedToolWindow Non-resizable tool window borders

1.2.3 Control the display position of the form (StartPosition property)

StartPosition properties and descriptions
attribute value illustrate
CenterParent The form is centered on its parent form
CenterScreen The form is centered in the currently displayed window and has the dimensions specified in Window Size
Manual The position of the form is determined by the Location property
WindowsDefaultBounds The form is positioned in the Windows default position, and its boundaries are also determined by Windows default
WindowsDefaultLocation The form is positioned in the windows default position and its dimensions are specified in Window Size

1.2.4 Setting of form background image

The background can be set by settingBackgroundImage property, and the background style property can be set by BackgroundImageLayoutSettings

BackgroundImageLayout properties and descriptions
attribute value illustrate
Tile (default) Background image repeats
None The background image is displayed on the left
None while the RightToLeft property is set to Yes The background image is displayed on the right
Center The background image is displayed in the center
Stretch background image lashing
Zoom The background image is scaled up to the appropriate size

1.2.5 Showing and hiding forms

Form1 f=New Form1();//实例化对象
f.show(); //show()用于显示
f.Hide(); //Hide()用于隐藏

1.3 Form events

1.3.1 Click event (Click)

When the form is clicked, an event will be triggered. Find the location of the event in the location shown in the figure. Double-click it to set the event code.

 1.3.2 Loading event (Load)

When the form is loaded, the event that will be triggered can be found at a location similar to the picture above. To enter editing, double-click

1.3.3 Closing event (FormClosing)

When the form is closed, the event that will be triggered can be found at a location similar to the picture above. To enter editing, double-click

Supplement: Why is it shown that the window is still running when I close it the next time I start it?

According to my personal situation, when we use multiple windows, for example, the click event of the Form1 window adds the startup of the Form2 form, and then hides the Form1 form. For this reason, the Form2 form is closed with X , but in fact the Form1 form is still started in the background.

The solution to this problem occurs: 1. The most direct way is to restart the computer. 2. Press Ctrl+shift+esc keys at the same time to open the resource manager and find the corresponding process to close it.

How to avoid this problem: Add the closing of Form1 in the Form2 closing event. Close all windowsApplication.Exct();

 2. MDI form

Multiple-document interface (multiple-document interface) is referred to as MDI form. MDI forms are used to display multiple documents at the same time, with each document displayed in its own window.
The above is the official explanation. My personal understanding is to display multiple child forms in the parent form.

As shown below

 2.1 Set up MDI form

In an MDI form, the form that acts as a container is called the parent form, and other forms that can be placed in the parent form are called child forms, also called MDI child forms.

2.1.1 Set the parent form

To set a form as the parent form, just set the IsMdiContainer property to True in the form properties panel.

2.1.2 Set up subform

After setting the parent form, determine the child form through the MdiParent property in the parent form's startup event. The code example is as follows
 

        private void Form1_Load(object sender, EventArgs e)
        {
            Form2 frm2 = new Form2();
            frm2.Show();
            frm2.MdiParent = this; //展示在父窗口form1中,this表示本窗格
        }

2.2 Arrange MDI subforms

If there are multiple subforms open at the same time in an MDI form, if the order is not adjusted, the interface will be very confusing and not suitable for browsing. Can be set through the MdiLayout enumeration.

MdiLayout sheets
enumeration value illustrate
ArrangeIcons Arrange all MDI child window icons
Cascade All MDI sub-windows are arranged in a cascading manner
TileHorizontal Tile child windows horizontally
TileVerttical Vertically tiled windows

The case code is as follows
 

LayoutMdi(MdiLayout.TileHorizontal);//水平平铺
LayoutMdi(MdiLayout.TileVertical);//垂直排列

3. Form controls

1.1 Overview of controls

Common controls includetext controls, selection controls, group controls, menu controls, toolbar controls and status bar controls
 

The functions of common controls
Control classification effect
text control Text controls can display text on the control
Select control Mainly provides users with selected items
Group controls Use group controls to group other controls in the form
menu control Make function menus for your system to group application commands and make them easier to access
toolbar control Provides commonly used related tools in the main menu
status bar control Used to display information about objects on a form, or can display information about an application

1.2 Related operations of controls

I will not describe adding and deleting controls here, I will only talk about a locking control. After completing the settings of the locked form, in order to avoid misoperation and changing the control settings of the form, the controls can be positioned by locking the controls.
In the properties window of the control, click the Locked property and select true to lock the control

2.1 Text control

Text controls mainly include Label control (label control), Button control (button control), TextBox control (text box control) and RichTextBox control (formatted text control)

2.1.1Label control

a)Overview: is mainly used to display text that cannot be edited by the user. You can also set the text information to be displayed by writing code.

 c)Show/hide the control:By setting the visible attribute (true is displayed\false is hidden)

2.1.2Button control

a)Overview:Allows users to perform operations from a single machine. Both text and images can be displayed.

b)Response to the click event of the button:A click event is triggered when the button is clicked, and the code in the click event is executed.

c)Set the button as the form's "enter" button:Set the form's AcceptButton property, each time you press the enter key, you click this button

this.AcceptButton=button1

d)Set the button as the "esc" button:By setting the form's CancelButton Attribute, each time you press the esc key, you click this button  

this.cancelButton=button1

Supplement:If you want to move the mouse in and out of the button, and change the style or font style of the button, you can use the OnMouseEnter (move in) and OnMouseLeave (move out) events.

2.1.3TextBox control

  a)Overview: is used to obtain user-entered data or display text. Text box controls are typically used for editable text, but can also be made read-only. A text box can display multiple lines, and text can be wrapped to fit the size of the control.

b)Create a read-only text box:By setting the ReadOnly property, you can set whether the text box is read-only. (Code modifications are in the folder)

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.ReadOnly = true;   //将文本设置为只读
            textBox1.Text = "你好世界";
        }

c)Create a password text box:By setting PasswordChar (the display symbol can be customized) or UseSystremPasswordChar (displayed as 'large Black spot')

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.PasswordChar = '#';    //设置文本框的密码字符为@
            textBox1.UseSystemPasswordChar = true;   //此密码字符为大黑点
        }

d)Create a multi-line text box:By setting the Multiline property (true to open, false to close)

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Multiline = true;    //使其显示多行
            textBox1.Height = 20;         //设置文本框的行高
        }

e)Highlight text:Set the highlighted text by setting the SelectionStart (starting index) and SelectionLength (character length) properties (simple In other words, it is the selected state)

        private void Form1_Load(object sender, EventArgs e)
        {
            textBox1.Multiline = true;    //使其显示多行
            textBox1.SelectionStart = 0;  //其实索引
            textBox1.SelectionLength = 5; //字符长度
            textBox1.Height = 20;         //设置文本框的行高
        }

f)The text change event of the responsive text box:When the text in the text box changes, the text box's event will be triggered. TextChanged event. For example, Label1.Text=textBox1.Text; Label displays the same content as TextBox

2.1.4RichTextBox control

 Overview: The control is used to display, enter, and manipulate formatted text. In addition to performing all the functions of a TextBox control, you can also display fonts, colors, and links, load text and embedded images from files, undo and repeat editing operations, and find specified characters.

a)Display the scroll bar in the RichTextBox control:Set the Multiline property to true to display the scroll bar and false to not display it. The default is True; scroll bars are divided into horizontal scroll bars and vertical scroll bars. By setting the ScrollBars property, its property values ​​are as follows.

attribute value illustrate

Both

Horizontal or vertical scroll bars, or both, appear only when the text exceeds the width or length.

None

Never show scrollbars of any kind

Horizontal

Horizontal scroll bars appear only when the text exceeds the width of the control. The WordWrap property must be set to false for this to occur

Vertical

Show vertical scrollbar only when text exceeds control height

ForcedHorizontal

The horizontal scroll bar is only displayed when the wordWrap property is set to false. The scroll bar appears light gray when the text does not exceed the length of the control

ForcedVertical

Always show vertical scroll bars. When the text exceeds the length, the scrollbar is light gray

ForcedBoth

Always show vertical scroll bars. When the WordWrap property is set to false, a horizontal scroll bar is displayed. When the text exceeds the width or length of the control, both scroll bars appear gray.

Hyperlink style

           //在窗体启动时richTextBox1生成一个文本

        private void 超链接样式_Load(object sender, EventArgs e)
        {
            richTextBox1.Text = "百度 http://baidu.com";
        }




            //在LinkClicked事件中对网址进行样式改变
        private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            //实现内容中的网址带下划线
            System.Diagnostics.Process.Start(e.LinkText);

        }

richTextBox text box settings

private void Form1_Load(object sender, EventArgs e)
        {
            richTextBox1.Multiline = true;
            richTextBox2.Multiline = true;
            richTextBox3.Multiline = true;
            richTextBox4.Multiline = true;
            richTextBox5.Multiline = true;
            richTextBox6.Multiline = true;
            richTextBox7.Multiline = true;


            ///设置scrollbars属性,实现垂直水平滚动条。
            richTextBox1.ScrollBars = RichTextBoxScrollBars.Both; //只要超过才会显示


            richTextBox2.ScrollBars = RichTextBoxScrollBars.None; //从不显示


            richTextBox3.ScrollBars = RichTextBoxScrollBars.Horizontal;//超过并且WORDwrap为false才会显示水平滚动条


            richTextBox4.ScrollBars = RichTextBoxScrollBars.Vertical;//只有达到高度才会显示垂直滚动条


            richTextBox5.ScrollBars = RichTextBoxScrollBars.ForcedHorizontal;//超过并且WORDwrap为false才会显示水平滚动条,未达到为灰色


            richTextBox6.ScrollBars = RichTextBoxScrollBars.ForcedVertical;//始终显示垂直滚动条,未达到时为灰色


            richTextBox7.ScrollBars = RichTextBoxScrollBars.ForcedBoth;//始终显示垂直滚动条,WORDwrap为false才会显示水平滚动条。未达到时为灰色
        }

3.1 Select class controls

选择类控件主要包括ComboBox控件(下拉框)、CheckBox控件(多选框)、RidioButton控件(单选按钮)、NumericUpDown控件(数值选择控件)和ListBox控件(列表控件)。

3.1.1ComboBox控件

ComboBox控件用于在下拉组合框中显示数据。
ComboBox控件主要由两部分组成:一个允许用户输入列表项的文本框,一个列表框。

添加元素:分为手动和代码添加。

手动添加:
拖入ComboBox控件——选择控件上的小三角——编辑项
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("电视");
            comboBox1.Items.Add("电脑");
            comboBox1.Items.Add("空调");
            comboBox1.Items.Add("手表");
        }

设置下拉样式(DropDownStyle)

DropDownStyle属性说明
属性值 说明
Simple 使用下拉列表部分总是可见
DropDown(默认值) 使用户可以编辑控件的文本框部分,单击箭头才显示
DropDownList 用户不可编辑文本框部分,只能单击箭头选择一项
//代码参照格式
comboBox1.DropDownStyle= ComboBoxStyle.DropDownList;

当comboBox1选中时comboBox2下拉框内容随之改变
selectedItem是获取当前选中项的内容

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBox2.Items.Clear();  //删除所有下拉框的内容

            //判断comboBox1中的值对comboBox2中的值进行改变
            if (comboBox1.SelectedItem=="电视") 
            {
                comboBox2.Items.Add("戴尔");
                comboBox2.Items.Add("联想");
                comboBox2.Items.Add("华硕");
            }
            /*else if...*/
        }

3.1.2CheckBox控件

CheckBox控件用来表示是否选取了某个选项条件,常用于为用户提供具有是/否或真/假值的选项。

判断复选框是否选中/CheckedChanged事件进行状态更改响应

通过在控件的Click事件中判断CheckState属性的返回值,得知复选框是否被选中。CheckState属性的返回值有两个值:Checked表示控件处于选中状态Unchecked表示控件处于取消选中状态

也可直接调用Checked判断是否被选中,如果选择则为True反之为false;

CheckedChanged事件进行状态更改响应:当复选框控件状态发生改变时则会触发

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)  //checkBox1.CheckState==CheckState.Checked 同理
            {
                MessageBox.Show("选中");
            }
            else { MessageBox.Show("未选"); }
        }

3.1.3RadioButton单选按钮

RadioButton控件为用户提供两个或多个互斥选项组成的选项集。当用户选中某单选按钮时,一组中的其他单选按钮不能同时选定。
单选按钮必须在同一组中才能实现单选效果。

1、判断单选按钮是否被选中

可通过在控件的Click事件中判断Checked属性的返回值,可以判断单选按钮是否被选中。如果是选中状态则为true,反之为false。
 

        private void radioButton1_Click(object sender, EventArgs e)
        {
            if (radioButton1.Checked)
            {
                MessageBox.Show("yes");
            }
            else { MessageBox.Show("no"); }
        }


//在窗体加载事件中可以设置默认的选则单选按钮
radioButton1.Checked=True;

2、响应单选按钮选中状态更改事件

当控件的选中状态发生更改时,会引发控件的CheckedChanged事件

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            MessageBox.Show("单选按钮状态被修改");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            radioButton1.Checked = true;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            radioButton1.Checked=false;
        }

3、单选按钮分组

在多个需要不同的单选按钮的条件下,如果不进行分组,那么在整个界面中就只能一次选中一个。在进行不同的分组时即可在不同的组中进行单选的判定。

可以用Panel控件即可进行分组。它的使用就是将其拖着框住分组的单选按钮。

3.1.4NumericUpDown控件

NumericUpDown控件是一个显示和输入数值的控件。如下图所示

1、最大值/最小值设置

该控件的Maximum属性可以设置数值的最大值,如果输入的数值大于这个属性的值,程序将自动把数值改为设置的最大值。Minimum属性可以设置数值的最小值,该效果和最大值一致

2、获取NumericUpDown控件中显示的数值

 通过控件的Value属性,可以获取NumericUpDown空间中显示的数值
 

        private void Form1_Load(object sender, EventArgs e)
        {
            numericUpDown1.Maximum = 100;
            numericUpDown1.Minimum = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label1.Text=numericUpDown1.Value.ToString();
        }

3、设置NumericUpDown控件中数值的显示方式

DecimalPlaces属性用于确定在小数点后显示位数,默认为0
ThousandsSeparator属性用于确定是否每隔3个十进制数字就插入一个分隔符,默认为false
Hexadecimal属性设置为true则该控件可以用十六进制显示,默认为false

注:DecimalPlaces属性的值不能小于0,或大于99;否则会报错。

        private void Form1_Load(object sender, EventArgs e)
        {
            numericUpDown1.Maximum = 100;
            numericUpDown1.Minimum = 0;
            numericUpDown1.DecimalPlaces = 1;
        }

3.1.5ListBox控件

ListBox控件用于显示一个列表,用户可以从中选择一项或多项。如果选项总数超出可以显示的项数,则控件会自动添加滚动条。效果图如下

 

1、在ListBox控件中添加和移除项

通过ListBox控件的Items属性的Add()方法和Remove()方法,可以向ListBox控件中添加和删除项目。

        private void Form1_Load(object sender, EventArgs e)
        {
            listBox1.Items.Add("DNF");
            listBox1.Items.Add("消逝的光芒");
            listBox1.Items.Remove("英雄联盟");
        }

2、创建总显示滚动条的列表控件

通过设置控件的HorizontalScrollbar属性ScrollAlwaysVisible属性可以使控件总显示滚动条。前者为水平滚动条后者为垂直滚动条

        private void Form1_Load(object sender, EventArgs e)
        {
                //添加元素
            listBox1.Items.Add("DNF");
            listBox1.Items.Add("消逝的光芒");
                //删除元素
            listBox1.Items.Remove("英雄联盟");
                //添加水平滚动条
            listBox1.HorizontalScrollbar = true;
                //添加垂直滚动条
            listBox1.ScrollAlwaysVisible = true;
        }

3、在ListBox控件中选择多项

通过设置SelectionMode属性,可以在控件中选择多项。SelectionMode属性时SelectionMode枚举值之一,默认为SelectionMode.One。

SelectionMode枚举成员及说明
枚举成员 说明
MultiExtended 可以选择多项,并且用户可使用Shift键、CTRL键和箭头来选择
MultiSimple 可以选择多项
None 无法选择项
One 只能选择一项
        private void Form1_Load(object sender, EventArgs e)
        {
            listBox1.SelectionMode=SelectionMode.MultiExtended;
        }

4.1分组控件

4.1.1Panel控件

Panel控件用于为其他控件提供可识别的分组。该控件可以使窗体分类更详细,更便于理解,同时可依有滚动条。

        private void Form1_Load(object sender, EventArgs e)
        {
            panel1.Visible=false;       //隐藏控件
            richTextBox1.Text = " 对酒当歌,人生几何!\r\n\r\n譬如朝露,去日苦多。\r\n\r\n慨当以慷,忧思难忘。\r\n\r\n何以解忧?唯有杜康。\r\n\r\n青青子衿,悠悠我心。\r\n\r\n但为君故,沉吟至今。\r\n\r\n呦呦鹿鸣,食野之苹。\r\n\r\n我有嘉宾,鼓瑟吹笙。\r\n\r\n明明如月,何时可掇?\r\n\r\n忧从中来,不可断绝。\r\n\r\n越陌度阡,枉用相存。\r\n\r\n契阔谈讌,心念旧恩。\r\n\r\n月明星稀,乌鹊南飞。\r\n\r\n绕树三匝,何枝可依?\r\n\r\n山不厌高,海不厌深。\r\n\r\n周公吐哺,天下归心。 ";

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("请输入内容");
                textBox1.Focus();       //将光标定位到此控件内
            }
            else
            {
                panel1.Visible = true;
            }
        }

 效果展示

补充:如果将Panel控件的Enabled属性(设置控件是否可以对用户交互做出响应)设置为false,那么该容器中的所有控件将被设置为不可用状态

4.1.2GroupBox控件

GroupBox控件主要为其他控件提供分组,按照控件的分组来细分窗体的功能。
其在所包含的控件集周围总是显示边框,并且可以显示标题,但是GroupBox控件没有滚动条。

 4.1.3TabControl控件

TabControl控件用来添加多个选项卡,并可在选项卡上添加子控件。这样就可以把窗体设计成多页,使窗体功能划分为多个部分
选项卡中可以包含图片或其他控件。选项卡控件还可以用来创建用于设置一组相关的属性的属性页

TabControl控件包含选项卡页,TabPage控件表示选项卡。
TabControl控件的TabPages属性表示其中所有TabPage控件的集合。

Tabpages集合中TabPage选项卡的顺序反映了TabControl控件中选项卡的顺序

1、选项卡图片显示样式

通过TabControl控件和组成控件上各选项卡的TabPage对象属性,可更改Windows窗体中选项卡的外观。
如将TabControl控件的ImgeList属性设置为ImgeList控件,配合TabPange中ImageIndex属性对选项卡进行图片设置。
 

        private void Form1_Load(object sender, EventArgs e)
        {
            //设置控件的ImageList属性为ImageList1控件
            tabControl1.ImageList = imageList1;
            //将选项卡的图标和ImageList1图片位置索引进行对接。
            tabPage1.ImageIndex = 0;
            tabPage2.ImageIndex= 0;
            //设置选项卡显示的文本,设置其Text属性
            tabPage1.Text = "选项卡1";
            tabPage2.Text = "选项卡2";
        }

2、鼠标移入时弹出提示信息

将TabControl控件的ShowToolTips属性设置为true;然后在tabPage选项卡的ToolTipText属性中输入相关的提示信息即可。

        private void Form1_Load(object sender, EventArgs e)
        {
            //设置控件的ImageList属性为ImageList1控件
            tabControl1.ImageList = imageList1;
            //设置选项卡显示的文本,设置其Text属性
            tabPage1.Text = "选项卡1";
            tabPage2.Text = "选项卡2";
            tabControl1.ShowToolTips = true;
            //鼠标移入选项卡弹出提示
            tabPage2.ToolTipText = "这是选项卡2";
        }

3、将选项卡显示为按钮样式

只需要将TabConTrol控件的Appearance属性设置为Button或FlatButtons,即可设置!
 

        private void Form1_Load(object sender, EventArgs e)
        {
            //设置控件的ImageList属性为ImageList1控件
            tabControl1.ImageList = imageList1;
            //设置选项卡显示的文本,设置其Text属性
            tabPage1.Text = "选项卡1";
            tabPage2.Text = "选项卡2";
                //设置为按钮样式
            tabControl1.Appearance = TabAppearance.Buttons;
        }

 4、在选项卡中添加控件

通过tabPage选项卡的Controls属性的Add()方法,向选项中添加一个控件。也可直接将控件拖进去

        private void Form1_Load(object sender, EventArgs e)
        {
            //设置控件的ImageList属性为ImageList1控件
            tabControl1.ImageList = imageList1;
            //设置选项卡显示的文本,设置其Text属性
            tabPage1.Text = "选项卡1";
            tabPage2.Text = "选项卡2";


            Button bt1 = new Button();
            bt1.Text = "按钮1";


            tabPage1.Controls.Add(bt1);
        }

5.1菜单、工具栏和状态栏控件

菜单时窗体应用程序主要的用户界面要素,工具栏为应用提供了操作系统的界面,状态栏显示系统的一些状态信息。

5.1.1MenuStrip控件

MenuStrip控件是程序的主菜单。MenuStrip控件取代了先前版本的MainMenu控件,支持多文档界面、菜单合并、工具提示和溢出。
程序员可通过添加访问键、快捷键、选中标记、图像和分割条来增强菜单的可用性和可读性。

快捷键只需要在后面加个(&键位),使用ALT+键位即可使用

5.1.2弹出式菜单(ContextMenuStrip)

弹出式菜单也成为“右键快捷菜单”,在点击右键时弹出,其位置是由鼠标点击的位置来确定的。

5.1.3ToolStrip控件 (工具栏)

ToolStrip控件是.NET框架3.5以上增加的新控件。工具栏其实就是相当于工厂每个人的工具箱。

工具栏的下来菜单中有八中不同的类型

工具栏菜单类型及说明
类型 说明
Button 包含文本和图像中可让用户选择的项
Label 包含文本和图像的项,不可以让用户选择,可以显示超链接。
SplitButton 在Button的基础上增加了一个下来菜单
DropDowmButton 用于下拉菜单选择项
Separator 分隔符
ComboBox 显示一个下拉框
TextBox 显示一个文本框
ProgressBar 显示一个进度条

5.1.4StatusStrip控件(状态栏)

StatusStrip控件通常处于窗体发的最底部,用于显示窗体上对象的相关信息,或者可以显示应用程序的信息。
 

常用组合控件及说明
控件名 说明
StatusLabel 用于显示文本
ProgressBar 用于显示进度条
DropDowmButton 用于下拉菜单选择项
SplitButton 在Button的基础上增加了一个下来菜单
        private void Form1_Load(object sender, EventArgs e)
        {
            //在任务栏上显示日期
            toolStripStatusLabel1.Text = DateTime.Now.ToString();
            //进度条最大值与最小值设置
            toolStripProgressBar1.Minimum = 0;
            toolStripProgressBar1.Maximum = 100;

            toolStripProgressBar1.Step = 2;             //进度条的增值
            for (int i = 0; i < 100; i++)
            {
                toolStripProgressBar1.PerformStep();  //按照Step属性的数量增加进度栏的当前位置
            }
        }

6.1.1ImageList控件(图片集)

ImageList控件用于存储图像资源,并在控件上显示出来,这样就简化了对图像的管理。
ImageList控件实际上相当于一个图片集。在如pictureBox控件中展示对应的图片,且图片在ImageList控件中也是用索引来判断位置。

 一般ImageList控件都是与pictureBox控件结合出现,并且ImageList控件并不会在窗体中展示,他只是一个用于存放图片的容器。
图片可以手动放入和移除也可以通过代码加入和移除;

1、ImageList控件代码添加图片

通过ImageList控件的Images属性的Add()方法向控件中添加图像

        private void Form1_Load(object sender, EventArgs e)
        {
                //获取图片路径
            string a = "C:\\Users\\Promise\\Pictures\\4.jpg";
            Image b=Image.FromFile(a,true);
                //保存图片
            imageList1.Images.Add(b);
                //在pictureBox中展示图片,通过Images属性获取图片索引位置
            pictureBox1.Image = imageList1.Images[0];
        }

 2、在ImageList控件中通过代码移除图片

在ImageList控件中,RemoveAt()方法可以移除单个图像,使用Clear()方法可以移除所有图像。

        private void button1_Click(object sender, EventArgs e)
        {
            if (imageList1.Images.Count==0) //判断imagelist中是否存在图片
            {
                MessageBox.Show("没有图片");
            }
            else
            {
                imageList1.Images.RemoveAt(0);
                //RemoveAt(图片索引位置);
            }
        }

7.1PictureBox控件(图片展示)

PictureBox控件是用于显示图像在Windows窗体控件,通常用于在窗体的指定位置显示图片,它可手动添加图片,也可代码添加,并且多与ImageList控件结合出现。

PictureBox的常用属性
属性 说明
Image 用于设置显示在图片框控件上的图像
ImageLocation 用于设置在图片框控件上的图像路径
SizeMode 用于控制调整控件或图片的大小及放置位置
SizeMode的属性值
属性值 说明
Normal 图像被放置于空间的左上角,如果图片大于控件大小则超出部分被裁剪掉。
StretchImage 控件中的图像被拉伸或收缩,用于适应控件的大小
AutoSize 调整控件的大小,使其等于所包含的图像大小
CenterImage 如果图片小于空间,则居中显示,反之多出部分被裁剪。
Zoom 图像大小按其原有的长宽比例等比例方法或缩小

PictrueBox控件显示图片

        private void Form1_Load(object sender, EventArgs e)
        {
            //pictureBox1.Image = Image.FromFile("C:\\Users\\Promise\\Pictures\\9.jpg");
            //两者效果一致
            pictureBox1.ImageLocation = "C:\\Users\\Promise\\Pictures\\9.jpg";
        }

其区别在于Image属性是图像对象,而ImageLocation属性是图像路径,是文本型。

8.1Timer控件(计时器)

计时器Timer控件是指按用户定义的时间间隔引发事件的控件,简而言之程序每隔一段时间重复执行一个操作。

1、Timer控件的常用属性、方法和事件

Timer控件的常用属性、方法和事件
属性 说明
Interval 事件发送的间隔(频率),以毫秒为单位
Enable 设置计时器是否启用,布尔类型。
方法 说明
Start() 启动计时器
Stop() 停止计时器
事件 说明
Tick 定时间隔到自动引发的事件

 2、计时器Timer实现时间改变

创建一个Label控件获取当前时间DateTime.Now.ToString()。再通过Timer实现刷新时间获取

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = DateTime.Now.ToString(); //获取当前时间
            timer1.Enabled = true;            //启动Timer
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            label1.Text= DateTime.Now.ToString(); //根据设置的时间间隔刷新时间
        }

 9.1ListView控件(带图标的选项列表)

 ListView控件用于显示带图标的选项列表,可以显示大图标、小图标和数据。使用ListView控件可以创建类似Windows资源管理器右窗口的用户界面。

通过View属性可设置控件中显示的方法

View属性及说明
属性值 说明
Details 每个项显示在不同的行上,并带有关于列中所排列的各项的进一步信息。最左边的列包含一个小图标和标签,后面的列包含应用程序指定的子项。列显示一个标头,它可以显示列的标题。用户可以在运行时调整各列大小。
LargeIcon 每个项都显示为一个最大的图标,在它的下面有一个标签。这是默认的视图模式
List 每个项都显示为一个小图标,在它右边带一个标签,各项排列在列中,没有列标头
SmaLLIcon 每个项显示为一个小图标,在他右边带一个标签
Tile 每个项都显示为一个完整大小的图标,在它的右边带项标签和子项信息。显示的子项信息由应用程序指定。

1、在ListView控件中添加、移除项

1、添加项

可以使用控件Items属性的Add()方法向控件中添加项。

        private void Form1_Load(object sender, EventArgs e)
        {
            listView1.Items.Add("穿越火线");
            listView1.Items.Add("英雄联盟");
            listView1.Items.Add("CS·GO");
            listView1.Items.Add("消逝的光芒");
        }

 在控件中添加完项目后,可以用CheckBoxes属性显示复选框,以便用户可以选中要对其执行操作的项

2、移除项

通过控件中Items属性的ReMoveAt()或Clear()方法可以移除控件中的项。

        private void button1_Click(object sender, EventArgs e)
        {
            listView1.Items.RemoveAt(listView1.Items.Count - 1); //移除其中最后一项
            listView1.Items.RemoveAt(listView1.SelectedItems[0].Index); //移除选定的项
        }

 在删除控件中的项目前,必须对项目的个数进行判断。如果为0,则不进行项目的删除;否则会触发异常。

2、默认选择控件中的某一项

可以通过控件的Selected属性设置控件中的选择项。

        private void Form1_Load(object sender, EventArgs e)
        {
            listView1.Items.Add("穿越火线");
            listView1.Items.Add("英雄联盟");
            listView1.Items.Add("CS·GO");
            listView1.Items.Add("消逝的光芒");
            listView1.Items[3].Selected=true; //默认选择
                //Items[索引位置]
        }

3、为ListView控件中添加图标

需要结合ImageList控件来设置其图标。并结合控件的LargeImageList属性

        private void Form1_Load(object sender, EventArgs e)
        {
            listView1.LargeImageList = imageList1;   //设置控件LargeImageList属性
            listView1.Items.Add("穿越火线");
            listView1.Items.Add("英雄联盟");
            listView1.Items.Add("CS·GO");
            listView1.Items.Add("消逝的光芒");
            listView1.Items[0].ImageIndex= 0;       //给指定索引项获取指定索引位置的图片
            listView1.Items[1].ImageIndex= 1;

           // Items[项目索引].ImageIndex=图片索引;
        }

 4、在控件中启用平铺视图

使用平铺功能可以在图形信息和文本信息之间提供一种视觉平衡。
如果要使用平铺视图,需要将View属性设置为Tile,可以通过设置TileSize属性来调整平铺大小。

        private void Form1_Load(object sender, EventArgs e)
        {
            listView1.View = View.Tile;
            listView1.LargeImageList = imageList1;   //设置控件LargeImageList属性
            listView1.Items.Add("穿越火线");
            listView1.Items.Add("英雄联盟");
            listView1.Items.Add("CS·GO");
            listView1.Items.Add("消逝的光芒");
            listView1.Items[0].ImageIndex= 0;       //给指定索引项获取指定索引位置的图片
            listView1.Items[1].ImageIndex = 1;
            listView1.TileSize = new Size(500, 3); //设置控件平铺大小,(长,高)
        }

5、为ListView控件中的项分组

可以使用ListView组按字母顺序、日期或任何其他逻辑组合对项进行分组,从而简化大型列表的导航。
若要启用分组,首先必须在设计器中或以编程方式房间一个或多个组。

        private void Form1_Load(object sender, EventArgs e)
        {
            //创建两个组
            listView1.Groups.Add(new ListViewGroup("FPS",HorizontalAlignment.Left));
            listView1.Groups.Add(new ListViewGroup("5v5", HorizontalAlignment.Left));
            //添加项
            listView1.Items.Add("穿越火线");
            listView1.Items.Add("英雄联盟");
            listView1.Items.Add("CS·GO");
            listView1.Items.Add("消逝的光芒");
            //将项分配给组
            listView1.Items[0].Group = listView1.Groups[0];
            listView1.Items[2].Group = listView1.Groups[0];
            listView1.Items[3].Group = listView1.Groups[0];
            listView1.Items[1].Group = listView1.Groups[1];
        }

 如果想临时禁用分组功能,可以将ShowGroups属性设置为False

 10.1TreeView控件(树状节点)

TreeView控件可以为用户显示节点层次结构,每个节点又可以包含子节点,包含子节点的节点叫做父节点。

10.1.1TreeView常用属性和事件

TreeView常用属性和事件及说明
属性 说明
Name 获取或设置控件名称
Nodes 控件根节点集合
SelectedNode 获取或设置当前控件中选定的根节点
ImageList 获取或设置控件中搜使用的图像集,关联ImageList控件
ImageIndex 获取或设置树节点显示的图像,在ImageList图像集中的索引
SelectedImageIndex 获取或设置节点被选中时显示的图像,在ImageList图像集中的索引
方法 说明
AfterCollapse 在折叠树节点后触发
AfterExpand 在展开树节点后触发
AfterSelect 在更改选中节点后触发
Click 在单击控件时触发

10.1.2添加和删除树节点

1、添加树节点

使用Nodes属性的Add()方法,可以向控件中添加节点。

        private void Form1_Load(object sender, EventArgs e)
        {
            TreeNode tn1 = treeView1.Nodes.Add("商品");  //父节点
            TreeNode tn2 = new TreeNode("商品名");  //二级节点
            TreeNode tn3 = new TreeNode("可乐");   //三级节点
            tn1.Nodes.Add(tn2); //将二级节点放到父节点中
            tn2.Nodes.Add(tn3); //将三级节点放到二级节点中
            tn3.Nodes.Add("18元");  //在三级节点下新建一个四级节点
        }

 注:在上一级节点下新建一个节点,并且此节点下还要包含另个一节点则需要将其赋值给一个变量。

2、移除节点

使用Nodes属性Remove()方法可以从树节点集合中移除指定的树节点。

        private void button1_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode.Text == "商品") //如果为根节点则提示
            {
                MessageBox.Show("请选择要删除的子节点");
            }
            else
            {
                treeView1.Nodes.Remove(treeView1.SelectedNode); //删除选定的子节点
            }
        }

10.1.3获取TreeView控件中选中的节点

可以在控件的AfterSelect事件中,使用EventArgs对象返回对已单击节点对象的引用。通过检查TreeViewEventArg类(它包含与事件有关的数据),确定单机了那个节点

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string fill = e.Node.Text;
            MessageBox.Show("当前选中节点是" + fill);
            /* 也可以是一下方法
             TreeNode selectedNode=this.treeView1.SelectedNode;
             MessageBox.Show(selectedNode.Text);
             */
            //两者区别,前者是封装好的,后者则是调用其方法获取
        }

 注:在BeforeCheck(在选中树节点复选框前发生)或AfterCheck(再选中舒解带你复选框后发生)在以上事件中尽可能不要使用TreeNode.Checked属性。因为可能导致选中内容不一致。

10.1.4为TreeView控件中的节点设置图标

该控件可在每个节点旁显示图标;图标紧挨着节点文本的左侧。并且实现图标要结合ImageList图片集控件能更好的实现;代码如下:

        private void Form1_Load(object sender, EventArgs e)
        {
            TreeNode tn1 = treeView1.Nodes.Add("商品");  //父节点
            TreeNode tn2 = new TreeNode("商品名");  //二级节点
            TreeNode tn3 = new TreeNode("可乐");   //三级节点
            tn1.Nodes.Add(tn2); //将二级节点放到父节点中
            tn2.Nodes.Add(tn3); //将三级节点放到二级节点中
            tn3.Nodes.Add("18元");  //在三级节点下新建一个四级节点

            treeView1.ImageList = imageList1;  //TreeView1控件ImageList属性绑定指定的图片集
            treeView1.ImageIndex = 0; //确定正常和展开状态下的节点显示的图像
            treeView1.SelectedImageIndex = 1; //确定选定状态下节点显示的图像
        }

11.1DateTimePicker控件 (日期时间框)

DateTimePicker控件用于选择日期和时间,DateTimePicker控件只能选择一个时间,而不是连续的时间段,也可以直接输入日期和时间

11.1.1使用DateTimePicker控件显示时间

通过将控件的Format属性设置为Time,实现控件只显示时间。
Format属性用于获取或设置控件中显示的日期和时间格式。

DateTimePickerFormat枚举值及说明
枚举值 说明
Custom DateTimePicker控件以自定义格式显示日期和时间
Long DateTimePicker控件以用户操作系统设置的长日期格式显示日期和时间
Short DateTimePicker控件以用户操作系统设置的段日期格式显示日期和时间
Time DateTimePicker控件以用户操作系统设置的时间格式显示日期和时间
        private void Form1_Load(object sender, EventArgs e)
        {
            dateTimePicker1.Format = DateTimePickerFormat.Time;
            label1.Text = dateTimePicker1.Text;
        }

补:如果想在该控件内用按钮调整时间值,需要将ShowUpDown属性设置为true。

11.1.2自定义格式显示日期

通过设置DateTimePicker控件的CustomFormat属性,可自定义日期时间格式字符串。

注意:Format属性必须设置为DateTimePickerFormat.Custom,才能影响显示日期和时间的格式

        private void Form1_Load(object sender, EventArgs e)
        {
            dateTimePicker1.Format = DateTimePickerFormat.Custom;
            dateTimePicker1.CustomFormat = "MMMM dd,yyyy - dddd";
            label1.Text = dateTimePicker1.Text;
        }

11.1.3获取控件中选择的日期

调用控件的Text属性以返回与控件中的格式相同的完整值,或调用Value属性的适当方法来返回部分值。

这些方法包括Year、Month和Day等,使用ToString将信息转换成可现实给用户的字符串

        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = dateTimePicker1.Text;
            label2.Text=dateTimePicker1.Value.Year.ToString();  //年
            label4.Text=dateTimePicker1.Value.Month.ToString(); //月
            label6.Text=dateTimePicker1.Value.Day.ToString();   //日
        }

补:如果想要直接获取当前系统的日期和时间,可以使用Value属性下的ToShortDateString()和ToShortTimeString()方法。

12.1MonthCalendar控件(日历控件)

MonthCalendar控件提供了一个直观的图形化界面,可以让用户查看和设置日期。并且用鼠标拖拽可以选取一个连续的时间,包括起始时间和结束时间

12.1.1MonthCalendar控件显示周数

ShowWeekNumbers属性设置为True,实现控件中显示周数,也可直接在属性面板更改。

        private void Form1_Load(object sender, EventArgs e)
        {
            monthCalendar1.ShowWeekNumbers = true;
        }

12.1.2在MonthCalendar控件中显示多个月

该控件最多可同时显示12个月。默认为1个月,但可以通过设置CalendarDimensions属性置顶显示多少个月以及它们在空间中的排列方式。

注意:CalendarDimensions属性一次只显示一个日历年,并且最多可显示12个月。行和列的有效组合得到的最大乘积为12,对于大于12的值,将在最适合的基础上修改显示。

        private void Form1_Load(object sender, EventArgs e)
        {
            monthCalendar1.CalendarDimensions = new Size(12, 12);
        }

 12.1.3在MonthCalendar控件中选择日期范围

如果在控件中选择日期范围,必须在Datechanged事件中设置SelectionStart和SelectionEnd属性。这两个属性分别用于设置日期的其实和结束。

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
            label1.Text = monthCalendar1.SelectionStart.ToString();
            label2.Text = monthCalendar1.SelectionEnd.ToString();
        }

13.1ErrorProvider控件(验证文本框输入)

ErrorProvider控件可以在不打扰用户的情况下向用户显示有错误发生。当验证用户在窗体中的输入或显示数据集内的错误时,一般要用到此控件。

ErrorProvider控件通过SetError()方法设置指定控件的错误描述字符串。

1、验证文本框

此处用到textbox控件的Validating事件。此事件是在控件验证时发生

        private void textBox1_Validating(object sender, CancelEventArgs e)
        {
            if (textBox1.Text == "")
            {
                errorProvider1.SetError(textBox1, "不可为空");
            }
        }

 13.2HelpProvider控件(调用帮助文档)

HelpProvider控件可以将帮助文件(.htm文件或.chm文件)与windows应用程序相关联,为特定对话框或对话框中的特定空间提供区分上下文的帮助;可以打开帮助文件到特定部分,如目录、索引或搜索功能的主页。

通过这只控件的HelpNamespace属性以及SetShowHelp()方法,实现当按F1键时,打开指定的帮助文件。

        private void Form1_Load(object sender, EventArgs e)
        {
            string fill = "F:\\web代码\\炫酷.html"; //获取路劲
            helpProvider1.HelpNamespace = fill;     //设置控件的属性
            helpProvider1.SetShowHelp(this, true);  //设置SetShowHelp()方法是否显示指定控件的帮助信息
        }

13.3ProgressBar控件(进度条)

ProgressBar控件通过在水平放置的方框中显示适当数目的矩形,指示工作的进度。

ProgressBar控件属性及说明
属性 说明
value 表示操作过程中已完成的进度
Minimum 设置进度条最小值
Maximum 设置进度条最大值

注意:ProgressBar控件只能以水平方向显示,如果想改变控件的显示样式,可以用ProgressBarRenderer类来实现,如纵向进度条或在进度条上显示文本。

        private void Form1_Load(object sender, EventArgs e)
        {
            progressBar1.Minimum = 0;  //最小值
            progressBar1.Maximum = 1000; //最大值
            progressBar1.Step = 100;  //递增值,默认为10
            for (int i = 0; i <= 1000; i++) //循环递增
            {
                progressBar1.PerformStep(); //开始进度条递增
            }
        }

Guess you like

Origin blog.csdn.net/weixin_51263756/article/details/130613649