C#学习教程12——Windows窗体应用程序

12.Windows窗体应用程序

WinFormWindows Form的简称是基于.NET Framework平台的客户端PC软件开发技术一般使用C#编程。Windows应用程序与Windows操作系统的界面类似每个界面都是由窗体构成的并且能通过鼠标单击、键盘输入等操作完成相应的功能。

12.1 创建Windows窗体应用程序

  • 在Visual Studio 2019软件中点击创建新项目。

在这里插入图片描述

  • 选择Windows窗体应用点击下一步。

在这里插入图片描述

  • 设置配置信息后点击下一步。

在这里插入图片描述

  • 默认选择目标框架.NET Core 3.1后可完成Windows窗体应用程序的创建。

在这里插入图片描述

在每一个Windows窗体应用程序的项目文件夹中都会有一个默认的窗体程序Form1.cs并且在项目的Program.cs文件中指定要运行的窗体。

Program.cs 文件的代码如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            // 用于启动应用程序中可视的样式如果控件和操作系统支持那么 控件的绘制就能根据显不风格来实现
            Application.EnableVisualStyles();
            // 控件支持UseCompatibleTextRenderingproperty属性该方法将此属性设置为默认值
            Application.SetCompatibleTextRenderingDefault(false);
            // 用于设置在当前项目中要启动的窗体new Form1()即为要启动的窗体
            Application.Run(new Form1());
        }
    }
}

在Windows窗体应用程序中界面是由不同类型的控件构成的系统中默认的控件全部存放到工具箱中工具箱在视图选项卡下如下图所示。
在这里插入图片描述

在工具箱中将控件划分为公共控件、容器、菜单和工具栏、数据、组件、打印、对话框等。

12.2 窗体属性

每一个Windows窗体应用程序都是由若干个窗体构成的窗体中的属性主要用于设置窗体的外观。

在Windows窗体应用程序中右击窗体在弹出的右键菜单中选择属性弹出如下图所示的属性面板。

在这里插入图片描述

窗体的常用属性如下表所示。

属性作用
Design:Name用来获取或设置窗体的名称
布局:WindowState获取或设置窗体的初始可视状态取值有3种即Normal正常、Minimized最小化、Maximized最大化默认为Normal即正常显示
布局:StartPosition获取或设置窗体第一次出现时的位置取值有5种即Manual窗体位置由Location属性决定、CenterScreen屏幕居中、WindowsDefaultLocation Windows默认位置、WindowsDefaultBoundsWindows默认位置边界由Windows决定、CenterParent在父窗体中居中默认为WindowsDefaultLocation
窗口样式:Icon获取或设置窗体上显示的图标
窗口样式:MaximizeBox获取或设置窗体标题栏右上角是否有最大化按钮默认为True
窗口样式:MinimizeBox获取或设置窗体标题栏右上角是否有最小化按钮默认为True
外观:Text获取或设置窗口标题栏中的文字
外观:BackColor获取或设置窗体的背景色
外观:BackgroundImage获取或设置窗体的背景图像
外观:BackgroundImageLayout获取或设置图像布局取值有 5 种即None图片居左显示、Tile图像重复默认值、Stretch拉伸、Center居中、Zoom按比例放大到合适大小
外观:Font获取或设置窗体上文字的字体
外观:ForeColor获取或设置窗体上文字的颜色
行为:Enabled获取或设置窗体是否可用

下面实现一个简单的Windows窗体应用程序部分属性取值如下。

属性属性值
NameForm1
StartPositionCenterScreen
Text第一个窗体
MaximizeBoxFalse
MinimizeBoxFalse
Backgroundimageexample.jpg
BackgroundlmageLayoutStretch

在上述属性中除了背景图片 (Backgroundimage) 属性以外其他属性直接添加上表中对应的属性值即可。设置背景图片属性 Backgroimdlmage的方法是单击Backgroundimage属性后的按钮在弹出的对话框中单击“导入”按钮。

在这里插入图片描述

每一个Windows窗体应用程序在运行时仅能指定一个启动窗体设置启动窗体的方式是在项目的Program.cs文件中指定。具体的代码如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

最后按Ctrl+F5键运行程序效果如下图所示。

在这里插入图片描述

12.3 窗体事件

在窗体属性面板中单击闪电图标即可查看到窗体中的事件如下图所示。

在这里插入图片描述

事件作用
行为:Load窗体加载事件在运行窗体时即可执行该事件
操作:MouseClick鼠标单击事件
操作:MouseDoubleClick鼠标双击事件
鼠标:MouseMove鼠标移动事件
钥匙:KeyDown键盘按下事件
钥匙:KeyUp键盘释放事件
行为:FormClosing窗体关闭事件关闭窗体时发生
行为:FormClosed窗体关闭事件关闭窗体后发生

下面的例子通过事件操作改变窗体背景颜色。

  • 在事件界面中选中需要创建的事件并双击该事件右侧的单元格系统会自动为其生成对应事件的处理方法。

在这里插入图片描述

  • 设置好事件后会在窗体对应的代码文件中自动生成与事件对应的4个方法代码如下。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {

        }

        private void Form1_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}
  • 添加事件处理代码除了可以在属性面板中设置外使用代码设置的方式是使用this关键字代表当前窗体的实例。、
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            //设置窗体背景颜色为黑色
            this.BackColor = Color.Black;
        }

        private void Form1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //设置窗体背景颜色为蓝色
            this.BackColor = Color.Blue;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //设置窗体颜色为红色
            this.BackColor = Color.Red;
        }
    }
}
  • 设置启动窗体在Program.cs类中将Form1窗体设置为启动窗体。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            // 设置启动窗体
            Application.Run(new Form1());
        }
    }
}

12.4 窗体方法

自定义的窗体都继承自System.Windows.Form类能使用Form类中已有的成员包括属性、方法、事件等。

方法作用
void Show()显示窗体
void Hide()隐藏窗体
DialogResult ShowDialog()以对话框模式显示窗体
void CenterToParent()使窗体在父窗体边界内居中
void CenterToScreen()使窗体在当前屏幕上居中
void Activate()激活窗体并给予它焦点
void Close()关闭窗体

下面的例子实现在一个窗体中打开另外一个窗体。

  • 在项目中创建两个窗体。

在这里插入图片描述

  • 设置Form1窗体的事件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            //创建Form2窗体实例
            Form2 form2 = new Form2();
            //打开form2窗体
            form2.Show();
        }
    }
}
  • 设置Form2窗体的事件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_MouseClick(object sender, MouseEventArgs e)
        {
            //将窗体居中
            this.CenterToScreen();
        }

        private void Form2_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            //关闭窗体
            this.Close();
        }
    }
}
  • 将Form1窗体设置为启动窗体。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //设置启动窗体
            Application.Run(new Form1());
        }
    }
}

在使用窗体中的方法时需要注意如果是当前窗体需要调用方法直接使用 this关键字代表当前窗体通过this.方法名(参数列表)的方式调用即可。如果要操作其他窗体则需要用窗体的实例来调用方法。

12.5 McssageBox消息框

在Windows窗体应用程序中向用户提示操作时采用消息框弹出的形式。消息框是通过McssageBox类来实现的定义了 Show 的多个重载方法该方法的作用就是弹出一个消息框。由于Show方法是一个静态的方法因此调用该方法只需要使用MessageBox.Show(参数)的形式即可弹出消息框。

方法说明
DialogResult Show(string text)指定消息框中显示的文本text
DialogResult Show(string text, string caption)指定消息框中显示的文本text以及消息框的标题caption
DialogResult Show(string text, string caption, MessageBoxButtons buttons)指定消息框中显示的文本text、消息框的 标题caption以及消息框中显示的按钮 buttons
DialogResult Show(string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon)指定消息框中显示的文本text、消息框的 标题caption 、消息框中显示的按钮 buttons以及消息框中显示的图标icon

在上面所列出方法的参数中涉及两个枚举类型MessageBoxButtons和MessageBoxIcon。

MessageBoxButtons枚举类型主要用于设置消息框中显示的按钮具体的枚举值如下

  • OK在消息框中显示“确定”按钮。
  • OKCancel在消息框中显示“确定”和“取消”按钮。
  • AbortRetryIgnore在消息框中显示“中止” “重试”和“忽略”按钮。
  • YesNoCancel在消息框中显示“是” “否”和“取消”按钮。
  • YesNo在消息框中显示“是”和“否”按钮。
  • RetryCancel在消息框中显示“重试”和“取消”按钮。

MessageBoxIcon枚举类型主要用于设置消息框中显示的图标具体的枚举值如下。

  • None在消息框中不显示任何图标。
  • Hand、Stop、Error在消息框中显示由一个红色背景的圆圈及其中的白色X组成 的图标。
  • Question在消息框中显示由圆圈和其中的一个问号组成的图标。
  • Exclamation、Warning在消息框中显示由一个黄色背景的三角形及其中的一个感叹号组成的图标。
  • Asterisk、Information在消息框中显示由一个圆圈及其中的小写字母i组成的图标。

调用 MessageBox 类中的Show方法将返回一个DialogResult类型的值。DialogResult也是一个枚举类型是消息框的返回值通过单击消息框中不同的按钮得到不同的消息框返回值。具体值如下。

  • None消息框没有返回值表明有消息框继续运行。
  • OK消息框的返回值是0K通常从标签为“确定”的按钮发送。
  • Cancel消息框的返回值是Cancel通常从标签为“取消”的按钮发送。
  • Abort消息框的返回值是Abort通常从标签为“中止”的按钮发送。
  • Retry消息框的返回值是Retry通常从标签为“重试”的按钮发送。
  • Ignore消息框的返回值是Ignore通常从标签为“忽略“的按钮发送。
  • Yes消息框的返回值是Yes通常从标签为“是“的按钮发送。
  • No消息框的返回值是No通常从标签为“否“的按钮发送。

下面的例子实现通过消息框提示打开新窗体。

  • 在项目中创建两个窗体。
  • 设置Form1窗体的事件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            //弹出消息框并获取消息框的返回值
            DialogResult dr = MessageBox.Show("是否打开新窗体", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            //如果消息框返回值是Yes显示新窗体
            if (dr == DialogResult.Yes)
            {
                Form2 form2 = new Form2();
                form2.Show();
            }
            //如果消息框返回值是No关闭当前窗体
            else if (dr == DialogResult.No)
            {
                //关闭当前窗体
                this.Close();
            }
        }
    }
}
  • 设置项目的启动窗体Form1。

12.6 控件

在Windows窗体应用程序中每个窗体都是由若干个控件构成的。控件就是指能输入文本的位置、能选择的位置、能单击的位置、图片显示的位置等。其中

  • 能输入文本的位置对应于Windows窗体应用程序中的文本框、多行文本框等。
  • 能选择的位置对应于Windows窗体应用程序中的复选框、单选按钮、下拉列表框。
  • 能单击的位置对应于Windows窗体应用程序中的按钮、超链接标签、菜单栏、工具栏等。
  • 图片显示的位置对应于Windows窗体应用程序中的图片控件。

12.7 Label和LinkLabel标签控件

通常使用标签控件来显示文本标签控件王要分为普通的标签Label和超链接形式的标签LinkLabel 。

属性名作用
Name标签对象的名称区别不同标签唯一标志
Text标签对象上显示的文本
Font标签中显示文本的样式
ForeColor标签中显示文本的颜色
BackColor标签的背景颜色
Image标签中显示的图片
AutoSize标签的大小是否根据内容自动调整True为自动调整False为用户自定义大小
Size指定标签控件的大小
Visible标签是否可见True 为可见False 为不可见

普通标签控件Label中的事件与窗体的事件类似常用的事件主要有鼠标单击事件、 鼠标双击事件、标签上文本改变的事件等。

超链接标签控件LinkLabel也具有相同的属性和事件主要应用的事件是鼠标单击事件。

下面的例子实现通过超链接单击事件交换两个普通标签的文本信息。

  • 在工具箱中设置控件并修改文本信息。

在这里插入图片描述

在这里插入图片描述

  • 双击超链接文本创建点击事件。

在这里插入图片描述

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
		// 超链接点击事件
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //交换标签上的信息。
            string temp = label1.Text;
            label1.Text = label2.Text;
            label2.Text = temp;
        }
    }
}

12.8 TextBox文本框控件

文本框TextBox是在窗体中输入信息时最常用的控件通过设置文本框属性可以实现多行文本框、密码框等。

属性名作用
Text文本框对象中显示的文本
MaxLength在文本框中最多输入的文本的字符个数
WordWrap文本框中的文本是否自动换行如果是True则自动换行如果是False则不能自动换行
PasswordChar将文本框中出现的字符使用指定的字符替换通常会使用*字符
Multiline指定文本框是否为多行文本框如果为True则为多行文本框如果为False则为单行文本框
ReadOnly指定文本框中的文本是否可以更改如果为True则不能更改即只读文本框如果为False则允许更改文本框中的文本
Lines指定文本框中文本的行数
ScrollBars指定文本框中是否有滚动条如果为True则有滚动条如果为False 则没有滚动条

文本框控件最常使用的事件是文本改变事件(TextChange)即在文本框控件中的内容改变时触发该事件。

下面的例子实现简单的登录窗体。

  • 设置控件信息。

在这里插入图片描述

            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(310, 112);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(125, 27);
            this.textBox1.TabIndex = 0;
            // 
            // textBox2
            // 
            this.textBox2.Location = new System.Drawing.Point(310, 174);
            this.textBox2.Name = "textBox2";
			// 密码框将用户输入的密码用*替代
            this.textBox2.PasswordChar = '*';
            this.textBox2.Size = new System.Drawing.Size(125, 27);
            this.textBox2.TabIndex = 1;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(240, 113);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(69, 20);
            this.label1.TabIndex = 2;
            this.label1.Text = "用户名";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(240, 175);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(54, 20);
            this.label2.TabIndex = 3;
            this.label2.Text = "密码";
            // 
            // linkLabel1
            // 
            this.linkLabel1.AutoSize = true;
            this.linkLabel1.Location = new System.Drawing.Point(310, 266);
            this.linkLabel1.Name = "linkLabel1";
            this.linkLabel1.Size = new System.Drawing.Size(39, 20);
            this.linkLabel1.TabIndex = 4;
            this.linkLabel1.TabStop = true;
            this.linkLabel1.Text = "登录";
            this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked); 
  • 设置超链接点击事件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //获取用户名
            string username = textBox1.Text;
            //获取密码
            string password = textBox2.Text;
            //判断用户名密码是否正确
            if ("Kint".Equals(username) && "1111".Equals(password))
            {
                MessageBox.Show("登录成功");
            }
            else
            {
                MessageBox.Show("登录失败");
            }
        }
    }
}

12.9 Button按钮控件

按钮主要用于提交页面的内容或者是确认某种操作等。常用的属性包括在按钮中显示的文字 (Text) 以及按钮外观设置的属性最常用的事件是单击事件。

下面的例子实现一个简单的用户注册功能并将提交的注册信息显示在新窗体的文本框中。

  • 设置Form1控件和Form2控件

在这里插入图片描述

在这里插入图片描述

  • 在注册时判断用户名和密码不能为空并且要求两次输入的密码一致设置Form1中的按钮代码如下。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //“确定”按钮的单击事件用于判断注册信息并跳转到新窗口显示注册信息
        private void button1_Click(object sender, EventArgs e)
        {
            string name = textBox1.Text;
            string pwd = textBox2.Text;
            string repwd = textBox3.Text;
            if (string.IsNullOrEmpty(name))
            {
                MessageBox.Show("用户名不能为空");
                return;
            }
            else if (string.IsNullOrEmpty(textBox2.Text))
            {
                MessageBox.Show("密码不能为空");
                return;
            }
            else if (!textBox2.Text.Equals(textBox3.Text))
            {
                MessageBox.Show("两次输入的密码不一致");
                return;
            }
            //将用户名和密码传递到Form2中
            Form2 form2 = new Form2(name, pwd);
            form2.Show();
        }
        //“取消”按钮的事件用于关闭窗体
        private void button2_Click(object sender, EventArgs e)
        {
            //关闭窗体
            this.Close();
        }
    }
}
  • 设置Form2中的代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form2 : Form
    {
        public Form2(string name, string pwd)
        {
            InitializeComponent();
            label2.Text = "用户名" + name;
            label3.Text = "密  码" + pwd;
        }
    }
}

12.10 RadioButton单选按钮控件

RadioButton是单选按钮控件多个RadioButton控件可以为一组这一组内的RadioButton控件只能有一个被选中。

下面通过一个例子使用单选按钮控件。

  • 设置控件。

在这里插入图片描述

  • 设置确认按钮点击事件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
		// 单击“确定”按钮的事件
        private void button1_Click(object sender, EventArgs e)
        {
            string msg = "";
            if (radioButton1.Checked)
            {
                msg = radioButton1.Text;
            }
            else if (radioButton2.Checked)
            {
                msg = radioButton2.Text;
            }
            else if (radioButton3.Checked)
            {
                msg = radioButton3.Text;
            }
            MessageBox.Show("您喜欢的编程语言是" + msg, "提示");
        }
    }
}

Checked属性可用于判断单选按钮是否被选中。如果该属性的返回值为True则代表选中如果返回值为False则表示未选中。

在这里插入图片描述

12.11 CheckBox复选框控件

复选框主要的属性有

  • Name表示这个组件的名称
  • Text表示这个组件的标题
  • Checked表示这个组件是否已经选中。

主要的事件就是CheckedChanged事件。

下面通过一个例子使用复选框控件。

  • 设置控件。

在这里插入图片描述

  • 设置点击事件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string msg = "";
            // 界面上的每一个控件都继承自Control类
            foreach (Control c in Controls)
            {
                //判断控件是否为复选框控件
                if (c is CheckBox)
                {
                    if (((CheckBox)c).Checked)
                    {
                        msg = msg + " " + ((CheckBox)c).Text;
                    }
                }
            }
            if (msg != "")
            {
                MessageBox.Show("您选择的爱好是" + msg, "提示");
            }
            else
            {
                MessageBox.Show("您没有选择爱好", "提示");
            }
        }
    }
}

在这里插入图片描述

12.12 CheckedListBox复选列表框控件

复选列表框显示的效果与复选框类似但在选择多个选项时操作比一般的复选框更方便。

下面通过一个例子使用复选列表框控件。

  • 设置控件。

在这里插入图片描述

			// checkedListBox1
            // 
            this.checkedListBox1.FormattingEnabled = true;
			// 设置可选项
            this.checkedListBox1.Items.AddRange(new object[] {
            "苹果",
            "香蕉",
            "梨"});
            this.checkedListBox1.Location = new System.Drawing.Point(275, 135);
            this.checkedListBox1.Name = "checkedListBox1";
            this.checkedListBox1.Size = new System.Drawing.Size(165, 136);
            this.checkedListBox1.TabIndex = 18;
            // 
  • 设置按钮点击事件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string msg = "";
            for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
            {
                msg = msg + " " + checkedListBox1.CheckedItems[i].ToString();
            }
            if (msg != "")
            {
                MessageBox.Show("您购买的水果有" + msg, "提示");
            }
            else
            {
                MessageBox.Show("您没有选购水果", "提示");
            }
        }
    }
}

在这里插入图片描述

在使用复选列表框控件时需要注意获取列表中的项使用的是Checkedltems属性获取当前选中的文本上图中蓝色的区域使用的是 Selectedltem属性。

12.13 ListBox列表框控件

列表框 (ListBox) 将所提供的内容以列表的形式显示出来可以选择其中的一项或多项内容。

属性名作用
MultiColumn获取或设置列表框是否支持多列如果设置为 True则表示支持多列 如果设置为 False则表示不支持多列默认为 False
Items获取或设置列表框控件中的值
SelectedItems获取列表框中所有选中项的集合
SelectedItem获取列表框中当前选中的项
SelectedIndex获取列表框中当前选中项的索引索引从 0 开始
SelectionMode获取或设置列表框中选择的模式当值为 One 时代表只能选中一项 当值为 MultiSimple 时代表能选择多项当值为 None 时代表不能选 择当值为 MultiExtended 时代表能选择多项但要在按下 Shift 键后 再选择列表框中的项

列表框还提供了一些方法来操作列表框中的选项由于列表框中的选项是一个集合形式的列表项的操作都是用Items属性进行的。

  • Items.Add 方法用于向列表框中添加项
  • Items.Insert 方法用于向列表框中的指定位置添加项
  • Items.Remove 方法用于移除列表框中的项。

下面通过一个例子使用列表框控件。

  • 设置控件。

在这里插入图片描述

            // listBox1
            // 
            this.listBox1.FormattingEnabled = true;
            this.listBox1.ItemHeight = 20;
            this.listBox1.Location = new System.Drawing.Point(241, 145);
            this.listBox1.Name = "listBox1";
            this.listBox1.Size = new System.Drawing.Size(285, 164);
            this.listBox1.TabIndex = 18;
            this.listBox1.Items.AddRange(new object[] {"篮球","排球","游泳" });
            // 
  • 设置相应事件。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        // 将文本框中的值添加到列表框中
        private void button1_Click(object sender, EventArgs e)
        {
            // 当文本框中的值不为空时将其添加到列表框中
            if (textBox1.Text != "")
            {
                listBox1.Items.Add(textBox1.Text);
            }
            else
            {
                MessageBox.Show("请添加爱好");
            }
        }
        // 将列表框中的选中项删除
        private void button3_Click(object sender, EventArgs e)
        {
            // 由于列表框控件中允许多选所以需要循环删除所有已选项
            int count = listBox1.SelectedItems.Count;
            List<string> itemValues = new List<string>();
            if (count != 0)
            {
                for (int i = 0; i < count; i++)
                {
                    itemValues.Add(listBox1.SelectedItems[i].ToString());
                }
                foreach (string item in itemValues)
                {
                    listBox1.Items.Remove(item);
                }
            }
            else
            {
                MessageBox.Show("请选择需要删除的爱好");
            }
        }
    }
}
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: windows