文章目录
- 1. WinForm工程创建
- 2. 工具箱
- 3 窗体属性
- 4. 窗体事件
- 5. 窗体方法
- 6. 消息框MessageBox
- 7. 标签Label、LinkLabel
- 8. 文本框TextBox
- 9 按钮Button、单选框RadioButton、复选框CheckBox、复选列表框CheckedListBox
- 10. 列表框ListBox
- 11. 下拉列表框ComboBox
- 12. 图片框PictureBox
- 13. 定时器Timer
- 14. 日期时间DateTimePicker
- 15 日历MonthCalendar
- 16. 菜单栏MenuStrip
- 17. MDI窗体
- 18 颜色控件ColorDialog
- 19 字体控件FontDialog
- 20. 打开文件与保存文件OpenFileDialog和SaveFileDialog
- 21 表格布局器TableLayoutPanel
- 22 排列布局器FlowLayoutPanel
- 23 打开文件对话框openFileDialog
- 24 颜色对话框colorDialog
- 25 数字选择器NumericUpDown
- *. 常见异常
- TODO
-
WinForm 是 Windows Form 的简称,是基于 .NET Framework 平台的客户端(PC软件)开发技术,是
C#
语言中的一个重要应用。 -
.NET 提供了大量 Windows 风格的控件和事件,可以直接拿来使用。
1. WinForm工程创建
Visual Studio中新建项目 - 选择Windows窗体应用。
在每一个 Windows 窗体应用程序的项目文件夹中,都会有一个默认的窗体框架代码文件 Form1.cs 和 窗体代码文件 Program.cs ,其包含了工程的起始代码框架.
注:每一个 Windows 窗体应用程序在运行时仅能指定一个启动窗体,设置启动窗体的方式是在项目的 Program.cs 文件中的main函数中指定。
- 新建WinForm工程后,Program.cs 中的默认代码框架为:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormLearning // 项目名
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles(); // 配置程序样式
Application.SetCompatibleTextRenderingDefault(false); // 配置控件参数
Application.Run(new Form1()); // 启动WinForm程序的启动窗体 Form1
}
}
}
1.1 打开窗体设计器
在代码中右击 - 查看设计器,即可打开窗体设计器。
1.2 打开代码编辑界面
与1.1.1 节
相反,在窗体设计器界面右击任意地方,选择“查看代码”,即可进入代码编辑界面;
2. 工具箱
菜单栏 - 视图 - 工具箱(快捷键:Ctrl +Alt +X),可查看可用的控件,若工具箱无控件,右击窗口选择”显示全部“。
在右键菜单中选择“选择项”命令,弹出如下图所示的对话框。
在该对话框中列出了不同组件中所带的控件,如果需要在工具箱中添加,直接选中相应组件名称前的复选框即可。
如果需要添加外部的控件,则单击“浏览”按钮,找到相应控件的 .dll 或 .exe 程序添加即可。
3 窗体属性
在 Windows 窗体应用程序中右击窗体或控件,在弹出的右键菜单中 选择“属性”命令,弹出如下图所示的属性面板。
窗体的常用属性如下表所示。
属性 | 作用 |
---|---|
Name | 窗体/空间的名称 |
WindowState | 获取或设置窗体的窗口状态,取值有3种,即Normal(正常)、Minimized(最小化)、Maximized(最大化),默认为 Normal,即正常显示 |
StartPosition | 获取或设置窗体运行时的起始位置,取值有 5 种,即 Manual(窗体位置由 Location 属性决定)、CenterScreen(屏幕居中)、WindowsDefaultLocation( Windows 默认位置)、WindowsDefaultBounds(Windows 默认位置,边界由 Windows 决定)、CenterParent(在父窗体中居中),默认为 WindowsDefaultLocation |
Text | 窗口标题栏中的文字 |
MaximizeBox | 获取或设置窗体标题栏右上角是否有最大化按钮,默认为 True |
MinimizeBox | 获取或设置窗体标题栏右上角是否有最小化按钮,默认为 True |
BackColor | 获取或设置窗体的背景色 |
BackgroundImage | 获取或设置窗体的背景图像 |
BackgroundImageLayout | 获取或设置图像布局,取值有 5 种,即 None(图片居左显示)、Tile(图像重复,默认值)、Stretch(拉伸)、Center(居中)、Zoom(按比例放大到合适大小) |
Enabled | 获取或设置窗体是否可用 |
Font | 获取或设置窗体上文字的字体 |
ForeColor | 获取或设置窗体上文字的颜色 |
Icon | 获取或设置窗体上显示的图标 |
3.1 实例:创建一个新窗体
- 添加新Windows窗体
- 在窗体属性框内进行如下配置,在配置Backgroundimage时选择”本低资源“ - 导入指定窗体背景图片
属性 | 属性值 |
---|---|
Name | TestForm |
StartPosition | CenterScreen |
Text | 第一个窗体 |
MaximizeBox | False |
MinimizeBox | False |
Backgroundimage | 导入指定背景图片 |
BackgroundlmageLayout | Stretch |
Size | 265, 347(可调整) |
- 设置该窗体为启动窗体
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormLearning // 项目名
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new TestForm()); // 启动WinForm程序 TestForm
}
}
}
- 启动程序
4. 窗体事件
在 Windows 窗体应用程序中系统已经自定义了一些事件,在窗体属性面板中单击闪电图标即可查看到窗体中的事件。
窗体中常用的事件为:
事件 | 作用 |
---|---|
Load | 窗体加载事件,在运行窗体时即可执行该事件 |
MouseClick | 鼠标单击事件 |
MouseDoubleClick | 鼠标双击事件 |
MouseMove | 鼠标移动事件 |
KeyDown | 键盘按下事件 |
KeyUp | 键盘释放事件 |
FormClosing | 窗体关闭事件,关闭窗体时发生 |
FormClosed | 窗体关闭事件,关闭窗体后发生 |
4.1 实例:通过窗体的不同事件改变窗体的背景颜色
- 在事件属性中选择对应的窗体事件,双击该事件右侧的单元格,系统会自动为其生成对应事件的处理方法。
以下配置该窗体的鼠标单击、鼠标双击事件,生成处理方法如下:
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 WinFormLearning
{
public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
}
private void TestForm_MouseClick(object sender, MouseEventArgs e)
{
}
private void TestForm_MouseDoubleClick(object sender, MouseEventArgs e)
{
}
}
}
- 添加事件处理代码:
窗体的背景颜色所对应的属性是 BackColor,使用代码设置的方式是使用this
关键字代表当前窗体的实例,BackColor 属性类型是 Color 枚举类型的:
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 WinFormLearning
{
public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
}
private void TestForm_MouseClick(object sender, MouseEventArgs e)
{
this.BackColor = Color.Red; // 设置窗体背景颜色为红色
}
private void TestForm_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.BackColor = Color.Black; // 设置窗体背景颜色为红色
}
}
}
- 启动程序
5. 窗体方法
自定义的窗体都继承自 System.Windows.Form 类,能使用 Form 类中已有的成员,包括属性、方法、事件等。
窗体中也有一些从 System.Windows.Form 类继承的方法,如下表所示:
方法 | 作用 |
---|---|
void Show() | 显示窗体 |
void Hide() | 隐藏窗体 |
DialogResult ShowDialog() | 以对话框模式显示窗体 |
void CenterToParent() | 使窗体在父窗体边界内居中 |
void CenterToScreen() | 使窗体在当前屏幕上居中 |
void Activate() | 激活窗体并给予它焦点 |
void Close() | 关闭窗体 |
5.1 实例:窗体方法使用
-
目标效果:使用上述创建的两个窗体Form1和TestForm,在 Form1 窗体中单击,弹出一个新窗体 TestForm。在新窗体中单击,将 TestForm 窗体居中,双击,关闭 TestForm 窗体。
-
Form1.cs:
// 设置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 WinFormLearning
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_MouseClick(object sender, MouseEventArgs e) // 鼠标单击事件
{
//创建TestForm窗体实例
TestForm newForm = new TestForm();
//打开TestForm窗体
newForm.Show();
}
}
}
- TestForm.cs
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 WinFormLearning
{
public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
}
private void TestForm_MouseClick(object sender, MouseEventArgs e)
{
this.CenterToScreen();
}
private void TestForm_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Close();
}
}
}
6. 消息框MessageBox
窗体的消息框通过 MessageBox 类来实现,在 MessageBox 类中仅定义了 Show 的多个重载方法,该方法的作用就是弹出一个消息框。由于 Show 方法是一个静态的方法,因此调用该方法只需要使用MessageBox.Show( 参数 )
的形式即可弹出消息框。消息框在显示时有不同的样式, 例如标题、图标、按钮等。
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 也是一个枚举类型,是消息框的返回值,通过单击消息框中不同的按钮得到不同的消息框返回值。
- DialogResult 枚举类型的具体值如下:
- None:消息框没有返回值,表明有消息框继续运行。
- OK:消息框的返回值是 0K (通常从标签为“确定”的按钮发送)。
- Cancel:消息框的返回值是 Cancel (通常从标签为“取消”的按钮发送)。
- Abort:消息框的返回值是 Abort (通常从标签为“中止”的按钮发送)。
- Retry:消息框的返回值是 Retry (通常从标签为“重试”的按钮发送)。
- Ignore:消息框的返回值是 Ignore (通常从标签为“忽略“的按钮发送)。
- Yes:消息框的返回值是 Yes (通常从标签为“是“的按钮发送)。
- No:消息框的返回值是 No (通常从标签为“否“的按钮发送)。
6.1 实例:Message的应用
创建一个名为MessageForm的新窗体,配置主窗体的鼠标单击事件如下:
MessageBox.Show("刷新中,请勿多次点击.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
7. 标签Label、LinkLabel
由于在窗体中无法直接编写文本,通常使用标签控件来显示文本。在 Windows 窗体应用程序中,标签控件王要分为普通标签 (Label) 和超链接形式标签 (LinkLabel) 。
7.1 属性
- design
- Name:对象的名称,区别不同标签唯一标识
- 布局:
- AutoSize:标签的大小是否根据内容自动调整
- Size:标签控件的大小
- 行为:
- Visible:初始状态下,标签是否可见
- 外观:
- Text:显示的文本
- Font:Text 的文本的样式
- ForeColor:Text 显示文本的颜色
- BackColor:控件的背景颜色
- Image:控件中显示的图片
- BorderStyle:边框样式
- TextAlign:文本对齐方式
普通标签控件 (Label) 中的事件与窗体的事件类似,常用的事件主要有鼠标单击事件、 鼠标双击事件、标签上文本改变的事件等。与普通标签控件类似,超链接标签控件 (LinkLabel) 也具有相同的属性和事件。超链接标签主要应用的事件是鼠标单击事件,通过单击标签完成不同的操作,也即是超链接的操作。
7.1 实例:标签事件
点击窗体内的一个超链接,它的内容与另一个连接内容对调。
- 创建一个窗体,在窗体内添加两个超链接并在Text属性中编辑其内容。
- 在超连接的事件中配置鼠标单击事件如下:
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_MouseClick(object sender, MouseEventArgs e)
{
//交换标签上的信息。
string temp = label1.Text;
label1.Text = label2.Text;
label2.Text = temp;
//Process.Start("http://www.baidu.com"); // 使用系统默认浏览器打开网址
}
}
}
8. 文本框TextBox
文本框 (TextBox) 是在窗体中输入信息时最常用的控件,通过设置文本框属性可以实现多行文本框、密码框等。除了前面Label、LinkLabel一节介绍的控件属性以外,文本框还有一些不同的属性, 如下表所示:
属性名 | 作用 |
---|---|
Text | 文本框对象中显示的文本 |
MaxLength | 在文本框中最多输入的文本的字符个数 |
WordWrap | 文本框中的文本是否自动换行,如果是 True,则自动换行,如果是 False,则不能自动换行 |
PasswordChar | 将文本框中出现的字符使用指定的字符替换,通常会使用“*”字符 |
Multiline | 指定文本框是否为多行文本框,如果为 True,则为多行文本框,如果 为 False,则为单行文本框 |
ReadOnly | 指定文本框中的文本是否可以更改,如果为 True,则不能更改,即只读文本框,如果为 False,则允许更改文本框中的文本 |
Lines | 指定文本框中文本的行数 |
ScrollBars | 指定文本框中是否有滚动条,如果为 True,则有滚动条,如果为 False, 则没有滚动条 |
文本框控件最常使用的事件是文本改变事件 (TextChange),即在文本框控件中的内容改变时触发该事件。
8.1 实例:文本框事件
- 目标:在文本框内输入内容,同时将内容显示在标签上。
在窗体中添加一个TextBox控件,在其事件属性中的TextChange事件中编写代码。
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_MouseClick(object sender, MouseEventArgs e)
{
Process.Start("http://www.baidu.com"); // 使用系统默认浏览器打开网址
}
private void label2_Click(object sender, EventArgs e)
{
// 交换标签上的信息。
string temp = label1.Text;
label1.Text = label2.Text;
label2.Text = temp;
}
private void textBox1_TextChanged(object sender, EventArgs e) //
{
// 将文本框中的文本值显示在标签中
label2.Text = textBox1.Text;
}
}
}
8.2 富文本框RichTextBox
实际开发中可能需要在读取文本信息时需要保留原有的文本格式,这时候就不能使用普通的文本控件 (TextBox) 了,而需要使用富文本框控件 (RichTextBox) 来完成。
RichTextBox 控件在使用时与 TextBox 控件非常类似,除具有TextBox 控件的所有功能外,还能设定文字颜色、字体和段落格式,支持字符串查找功能,支持rtf格式等功能。
此外,在 RichTextBox 控件中还提供了文件加载和保存的方法,不需要使用文件流即可完成对文件的读写操作。
- 例程:
richTextBox2.AppendText("********************------------------********************" + "\r");// 添加内容
richTextBox2.Clear();// 清空富文本框
- 实例:使用 RichTextBox 控件完成文件的打开与保存操作
往窗口添加RichTextBox控件。
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;
using System.Diagnostics;
using System.IO;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
}
private void button5_Click(object sender, EventArgs e)
{
DialogResult dr = openFileDialog1.ShowDialog();
//获取打开文件的文件名
string filename = openFileDialog1.FileName;
if (dr == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(filename))
{
richTextBox1.LoadFile(filename, RichTextBoxStreamType.PlainText);
}
}
private void button6_Click(object sender, EventArgs e)
{
DialogResult dr = saveFileDialog1.ShowDialog();
//获取所保存文件的文件名
string filename = saveFileDialog1.FileName;
if (dr == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(filename))
{
richTextBox1.SaveFile(filename, RichTextBoxStreamType.PlainText);
}
}
}
}
9 按钮Button、单选框RadioButton、复选框CheckBox、复选列表框CheckedListBox
9.1 属性
-
设计:
- Name:控件的名称(最好全英文,不能有空格)
-
布局:
- AutoSize:根据Text 自适应大小
-
行为:
- TabIndex:
-
外观:
- Text:控件上显示的文本
-
例程:
bt_PortFresh.Enabled = false; // 按钮变灰,不可触发
9.2 事件
双击设计器中的按钮,即可跳转到该按钮被按下的函数内;
9.1.1 实例:普通按钮单击事件
-
目标:设计一个用户注册界面,注册成功后弹出新界面显示用户名和密码。
-
Form1.cs :
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
}
private void confirmButton_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 mainForm = new Form2(name,pwd);
mainForm.Show();
}
}
}
- Form2.cs :
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 WinFormLearning
{
public partial class Form2 : Form
{
public Form2(string name, string pwd) // 窗体初始化函数
{
InitializeComponent();
label2.Text = name;
label4.Text = pwd;
}
}
}
9.2 单选框RadioButton
- 目标:使用 3 个单选按钮供用户选择,弹出新窗体显示用户选择的选项。
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
radioButton1.Text = "选项一";
radioButton2.Text = "选项二";
radioButton3.Text = "选项三";
}
private void button12_Click(object sender, EventArgs e)
{
string msg = "";
if (radioButton1.Checked) // 若radioButton1被选中
{
msg = radioButton1.Text; // 将radioButton中的Text传递给消息框
}
else if (radioButton2.Checked)
{
msg = radioButton2.Text;
}
else if (radioButton3.Checked)
{
msg = radioButton3.Text;
}
MessageBox.Show("你选择的选项是:" + msg, "提示");
}
}
}
9.3 复选框CheckBox
相对于RadioButton 单选框而言,CheckBox是可多选的复选框。
属性
- 设计:
- Name:表示这个控件的名称
- 外观:
- Text:这个组件的标题
- Checked:这个组件是否已经选中
- 目标:完成选择用户爱好的操作,并在消息框中显示所选的爱好。
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
checkBox1.Text = "篮球";
checkBox2.Text = "羽毛球";
checkBox3.Text = "游泳";
checkBox4.Text = "跑步";
checkBox5.Text = "健身";
checkBox6.Text = "足球";
}
private void button12_Click(object sender, EventArgs e)
{
string msg = "";
if (checkBox1.Checked) // 若checkBox1被选中
{
msg = msg + " " + checkBox1.Text;
}
if (checkBox2.Checked)
{
msg = msg + " " + checkBox2.Text;
}
if (checkBox3.Checked)
{
msg = msg + " " + checkBox3.Text;
}
if (checkBox4.Checked)
{
msg = msg + " " + checkBox4.Text;
}
if (checkBox5.Checked)
{
msg = msg + " " + checkBox5.Text;
}
if (checkBox6.Checked)
{
msg = msg + " " + checkBox6.Text;
}
if (msg != "")
{
MessageBox.Show("您选择的爱好是:" + msg, "提示");
}
else
{
MessageBox.Show("您没有选择爱好", "提示");
}
}
}
}
- 代码简化:当复选框更多时,代码将显得冗余。由于界面上的每一个控件都继承自 Control 类,故直接判断界面上的控件是否为复选框即可大大简化代码。
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
checkBox1.Text = "篮球";
checkBox2.Text = "羽毛球";
checkBox3.Text = "游泳";
checkBox4.Text = "跑步";
checkBox5.Text = "健身";
checkBox6.Text = "足球";
}
private void button12_Click(object sender, EventArgs e)
{
string msg = "";
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("您没有选择爱好", "提示");
}
}
}
}
9.4 复选列表框CheckedListBox
复选列表框显示的效果与复选框类似,但在选择多个选项时操作比一般的复选框更方便。
- 目标:使用复选列表框完成选购水果的操作。
关于复选列表框的内容在其属性中的items中添加。
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
}
private void button12_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("您没有选购商品!", "提示");
}
}
}
}
10. 列表框ListBox
列表框控件中有一些属性与前面介绍的控件不同,如下表所示:
属性名 | 作用 |
---|---|
MultiColumn | 获取或设置列表框是否支持多列,如果设置为 True,则表示支持多列; 如果设置为 False,则表示不支持多列,默认为 False |
Items | 获取或设置列表框控件中的值 |
SelectedItems | 获取列表框中所有选中项的集合 |
SelectedItem | 获取列表框中当前选中的项 |
SelectedIndex | 获取列表框中当前选中项的索引,索引从 0 开始 |
SelectionMode | 获取或设置列表框中选择的模式,当值为 One 时,代表只能选中一项, 当值为 MultiSimple 时,代表能选择多项,当值为 None 时,代表不能选 择,当值为 MultiExtended 时,代表能选择多项,但要在按下 Shift 键后 再选择列表框中的项 |
列表框还提供了一些方法来操作列表框中的选项,由于列表框中的选项是一个集合形式的,列表项的操作都是用 Items 属性进行的。
10.1 实例:ListBox应用
使用列表框列出所需的商品。
注:ListBox实现多选需要设置窗体的 SelectionMode 属性为 MultiSimple。
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
}
private void button12_Click(object sender, EventArgs e)
{
string msg = "";
for (int i = 0; i < listBox1.SelectedItems.Count; i++)
{
msg = msg + " " + listBox1.SelectedItems[i].ToString();
}
if (msg != "")
{
MessageBox.Show("您选择的商品是:" + msg, "提示");
}
else
{
MessageBox.Show("您没有选择商品", "提示");
}
}
}
}
10.2 实例:ListBox应用二
在上述实例的基础上添加两个按钮,一个负责向列表框中添加爱好,一个负责删除选中的列表项。
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
}
private void button12_Click(object sender, EventArgs e) // “开始下单”按钮
{
string msg = "";
for (int i = 0; i < listBox1.SelectedItems.Count; i++)
{
msg = msg + " " + listBox1.SelectedItems[i].ToString();
}
if (msg != "")
{
MessageBox.Show("您选择的商品是:" + msg, "提示");
}
else
{
MessageBox.Show("您没有选择商品", "提示");
}
}
private void button4_MouseClick(object sender, MouseEventArgs e) // “删除”按钮
{
//由于列表框控件中允许多选所以需要循环删除所有已选项
int count = listBox1.SelectedItems.Count; // 获取listBox内被选中的元素数量
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("请选择需要删除的商品!");
}
}
private void button3_MouseClick(object sender, MouseEventArgs e) // “添加”按钮
{
// 当文本框中的值不为空时将其添加到列表框中
if (textBox1.Text != "")
{
listBox1.Items.Add(textBox1.Text);
}
else
{
MessageBox.Show("请添加商品!");
}
}
}
}
11. 下拉列表框ComboBox
下拉列表框ComboBox也称组合框,用于选择所需的选项。使用组合框可以有效地避免非法值的输入。在组合框中常用的事件是改变组合框中的值时发生的,即组合框中的选项改变事件 SelectedlndexChanged。
在组合框中常用的属性如下表所示:
属性名 | 作用 |
---|---|
DropDownStyle | 获取或设置组合框的外观,如果值为 Simple,同时显示文本框和列表框,并且文本框可以编辑;如果值为 DropDown,则只显示文本框,通过鼠标或键盘的单击事件展开文本框,并且文本框可以编辑;如果值为 DropDownList,显示效果与 DropDown 值一样,但文本框不可编辑。默认情况下为 DropDown |
Items | 获取或设置组合框中的值 |
Text | 获取或设置组合框中显示的文本 |
MaxDropDownltems | 获取或设置组合框中最多显示的项数 |
Sorted | 指定是否对组合框列表中的项进行排序,如果值为 True,则排序, 如果值为 False,则不排序。默认情况下为 False |
- 例程:
ComboBox1.Items.Clear();// 清空
ComboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());// 添加多个内容
ComboBox1.SelectedIndex = 0;// 设定当前选定项的索引
MessageBox.Show("您选择了 " + comboBox1.SelectedItem.ToString() + "。");
11.1 实例:实现一个选择专业系统
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
comboBox1.Items.Add("计算机应用");
comboBox1.Items.Add("英语");
comboBox1.Items.Add("会计");
comboBox1.Items.Add("软件工程");
comboBox1.Items.Add("网络工程");
}
private void button12_MouseClick_1(object sender, MouseEventArgs e)
{
//判断文本框中是否为空,不为空则将其添加到组合框中
if (textBox1.Text != "")
{
//判断文本框中的值是否与组合框中的的值重复
if (comboBox1.Items.Contains(textBox1.Text))
{
MessageBox.Show("该专业已存在!");
}
else
{
comboBox1.Items.Add(textBox1.Text);
}
}
else
{
MessageBox.Show("请输入专业!", "提示");
}
}
private void button3_MouseClick_1(object sender, MouseEventArgs e)
{
//判断文本框是否为空
if (textBox1.Text != "")
{
//判断组合框中是否存在文本框中输入的值
if (comboBox1.Items.Contains(textBox1.Text))
{
comboBox1.Items.Remove(textBox1.Text);
}
else
{
MessageBox.Show("您输入的专业不存在", "提示");
}
}
else
{
MessageBox.Show("请输入要删除的专业", "提示");
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//当组合框中选择的值发生变化时弹出消息框显示当前组合框中选择的值
MessageBox.Show("您选择的专业是:" + comboBox1.Text, "提示");
}
}
}
12. 图片框PictureBox
在 Windows 窗体应用程序中显示图片时要使用 PictureBox,图片的设置方式与背景图片的设置方式相似。图片控件中图片的设置除了可以直接使用 ImageLocation 属性指定图片路径以外,还可以在代码中通过 Image.FromFile 方法来设置,语法如下:
图片控件的名称 .Image = Image. FromFile( 图像的路径 );
- 图片选择与父容器停靠:点击控件右上角:
12.1 属性
- 外观:
- Image:“获取或设置图片控件中显示的图片
- 异步
- ImageLocation:获取或设置图片控件中显示图片的路径
- 行为:
- SizeMode:获取或设置图片控件中图片显示的大小和位置,如果值为 Normal,则图片显不在控件的左上角;如果值为 Stretchimage,则图片在图片控件中被拉伸或收缩,适合图片的大小;如果值为AutoSize,则控件的大小适合图片的大小;如果值为 Centerimage,图片在图片控件中居中;如果值为 Zoom,则图片会自动缩放至符合图片控件的大小
- 布局:
- dock:停靠方式
12.2 实例:一键实现图片交换
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
}
private void button12_Click(object sender, EventArgs e)
{
//定义中间变量存放图片地址,用于交换图片地址
PictureBox pictureBox = new PictureBox();
pictureBox.Image = pictureBox1.Image;
pictureBox1.Image = pictureBox2.Image;
pictureBox2.Image = pictureBox.Image;
}
}
}
13. 定时器Timer
在 Windows 窗体应用程序中,定时器控件(Timer)与其他的控件略有不同,它并不直接显示在窗体上,而是与其他控件连用,表示每隔一段时间执行一次 Tick 事件
。定时器控件常用的方法为启动定时器(Start)、停止定时器(Stop).
13.1 属性
- 行为
- Interval:设置计时时间间隔,以毫秒为单位
13.2 事件
// Tick 方法,根据`Interval` 参数,定时进入Tick 函数
private void timer1_Tick(object sender, EventArgs e)
{
//...
}
13.3 相关方法
timer1.Start();//开始定时
timer1.Stop();//停止定时
13.1 实例:实现图片每秒切换一次的功能
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
//设置当前图片空间中显示的图片的flag
//如果是图片1 flag的值为FALSE
//如果是图片2 flag的值为TRUE
bool flag = false;
public Form1() // 窗体初始化函数
{
InitializeComponent();
timer1.Interval = 2000; // 设置每隔x毫秒调用一次定时器Tick事件,单位ms
}
private void timer1_Tick(object sender, EventArgs e)
{
//当flag的值为TRUE时将图片控件的Image属性切换到Timer1.jpg
//否则将图片的Image属性切换到Timer2.jpg
if (flag)
{
pictureBox1.Image = Image.FromFile(@"C:\\Users\\xx\\Desktop\\微信截图_20210104135037.png");
flag = false;
}
else
{
pictureBox1.Image = Image.FromFile(@"C:\\Users\\xx\\Desktop\\微信截图_20210105144222.png");
flag = true;
}
}
private void button12_Click(object sender, EventArgs e)
{
timer1.Start(); // 启动定时器
}
private void button3_Click(object sender, EventArgs e)
{
timer1.Stop(); // 关闭定时器
}
}
}
14. 日期时间DateTimePicker
日期时间DateTimePicker控件用于在界面上显示当前的时间。日期时间控件中常用的属性是设置其日期显示格式的 Format 属性。
- Format 属性提供了 4 个属性值,如下所示。
- Short:短日期格式,例如2017/3/1;
- Long:长日期格式,例如2017年3月1日;
- Time:仅显示时间,例如,22:00:01;
- Custom:用户自定义的显示格式。
注:如果将 Format 属性设置为 Custom 值,则需要通过设置 CustomFormat 属性值来自定义显示日期时间的格式。
14.1 实例:在窗体上设置动态的日期时间(使用定时器)
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
//设置日期时间控件中仅显示时间
dateTimePicker1.Format = DateTimePickerFormat.Time;
// 设置每隔x毫秒调用一次定时器Tick事件,单位ms
timer1.Interval = 1000;
//启动定时器
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
//重新设置日期时间控件的文本
dateTimePicker1.ResetText();
}
}
}
15 日历MonthCalendar
日历控件(MonthCalendar)用于显示日期。
15.1 实例:使用日历控件实现入职日期的选择
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
string msg;
public Form1() // 窗体初始化函数
{
InitializeComponent();
//显示日历控件
monthCalendar1.Show();
}
private void button3_MouseClick(object sender, MouseEventArgs e)
{
MessageBox.Show("你的入职时间是:" + msg, "提示");
}
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
//将选择的日期显示在文本框中
textBox1.Text = monthCalendar1.SelectionStart.ToShortDateString();
msg = monthCalendar1.SelectionStart.ToShortDateString();
//隐藏日历控件
//monthCalendar1.Hide();
}
}
}
16. 菜单栏MenuStrip
在窗体上添加菜单栏控件 MenuStrip到窗体,然后按需求进行编辑,添加一级菜单后还能添加二级菜单。如下图,其中:
- MenuItem:菜单项
- ComboBox:下拉菜单
- TextBox:文本框
关于MenuStrip的应用基本上与ContextMenuStrip相同。
16.1 右键菜单栏ContextMenuStrip
右键菜单ContextMenuStrip即右击某个控件或窗体时出现的菜单。上下文菜单在设置时直接与控件的 ContextMenuStrip 属性绑定即可。
在工具箱中添加ContextMenuStrip控件到窗体,下拉选择添加右击菜单的内容,其中:
- MenuItem:菜单项
- ComboBox:下拉菜单
- Separator:分隔线
- TextBox:文本框
点击菜单内容即可编辑,弹出的新子菜单可创建二集菜单。
点击”编辑项“,也可查看比较详细的编辑内容。
实例:ContextMenuStrip应用
- 目标:创建 Windows 窗体应用程序,并为该窗体创建上下文菜单,菜单项包括打开窗体、关闭窗体。
通过添加groupbox,将ContextMenuStrip绑定在该groupbox中(groupbox属性中的ContextMenuStrip选择对应ContextMenuStrip),还可以实现该右击菜单只能在groupbox中有效。
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
}
private void 打开窗口ToolStripMenuItem_Click(object sender, EventArgs e)
{
ContextMenuStrip menu1 = new ContextMenuStrip();
menu1.Show();
MessageBox.Show("你打开了窗口" , "提示");
}
private void 关闭窗口ToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
16.2 状态栏菜单StatusStrip
在 Windows 窗体应用程序中,状态栏菜单(StatusStrip)用于在界面中给用户一些提示。就像office中的状态栏一样。
在窗体中添加StatusStrip后,点击下拉菜单,其中包括标签(StatusLabel)、进度条(ProgressBar)、下拉列表按钮(DropDownButton)、分割按钮(SplitButton)。
16.3 工具栏ToolStrip
ToolStrip可以理解成一个占位符,就像是占着一个区域的位置,然后在其上面再添加功能按钮。
在窗体中添加ToolStrip后,点击下拉菜单即可添加对应控件。
17. MDI窗体
MDI (Multiple Document Interface) 窗体被称为多文档窗体,它是很多 Windows 应用程序中常用的界面设计。MDI窗体的应用是在原窗体的属性 IsMdiContainer 设置为 True. 也可以通过代码设置,代码如下:
this.IsMdiContainer = True;
17.1 实例:MDI窗体应用
创建一个新窗体。
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
Form3 t = new Form3();
t.MdiParent = this;
t.Show();
}
}
}
运行结果:
18 颜色控件ColorDialog
颜色控件(ColorDialog)用于对界面中的文字设置颜色。
18.1 实例:使用颜色控件完成文本框中字体颜色的设置
往窗体添加ColorDialog控件。
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
}
private void button3_Click(object sender, EventArgs e)
{
//显示颜色对话框
DialogResult dr = colorDialog1.ShowDialog();
//如果选中颜色,单击“确定”按钮则改变文本框的文本颜色
if (dr == DialogResult.OK)
{
textBox1.ForeColor = colorDialog1.Color;
}
}
}
}
19 字体控件FontDialog
字体控件 (FontDialog) 用于设置在界面上显示的字体。
19.1 字体控件FontDialog应用
往窗体添加FontDialog控件。
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;
using System.Diagnostics;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
//显示字体对话框
DialogResult dr = fontDialog1.ShowDialog();
//如果在对话框中单击“确认”按钮,则更改文本框中的字体
if (dr == DialogResult.OK)
{
textBox1.Font = fontDialog1.Font;
}
}
}
}
20. 打开文件与保存文件OpenFileDialog和SaveFileDialog
文件对话框(FileDialog)主要包括文件浏览对话框,以及用于查找、打开、保存文件的功能,与 Windows 中的文件对话框类似。
20.1 实例:打开一个记事本文件,并更改记事本中的内容,保存到文件中
在窗体中添加openFileDialog和saveFileDialog控件。
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;
using System.Diagnostics;
using System.IO;
namespace WinFormLearning
{
public partial class Form1 : Form
{
public Form1() // 窗体初始化函数
{
InitializeComponent();
}
private void button5_Click(object sender, EventArgs e)
{
DialogResult dr = openFileDialog1.ShowDialog();
//获取所打开文件的文件名
string filename = openFileDialog1.FileName;
if (dr == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(filename))
{
StreamReader sr = new StreamReader(filename); // StreamReader()定义在System.IO中
textBox1.Text = sr.ReadToEnd();
sr.Close();
}
}
private void button6_Click(object sender, EventArgs e)
{
DialogResult dr = saveFileDialog1.ShowDialog();
string filename = saveFileDialog1.FileName;
if (dr == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(filename))
{
StreamWriter sw = new StreamWriter(filename, true, Encoding.UTF8); // StreamWriter()定义在System.IO中
sw.Write(textBox1.Text);
sw.Close();
}
}
}
}
21 表格布局器TableLayoutPanel
- 添加“TableLayoutPanel”控件:工具箱 - 容器 - TableLayoutPanel
- 表格行列编辑:如下图,点击控件右上角:
21.1 属性
- 布局:
- Dock:停靠,窗口停靠在另一个窗口的方式
- 外观:
- CellBorderStyle:表格边框外观
22 排列布局器FlowLayoutPanel
FlowLayoutPanel 是一个容器,它将其他控件按顺序排列在一行中;
22.1 属性
- 布局:
- FlowDirection:对齐与排列方式
23 打开文件对话框openFileDialog
用于弹出打开文件的窗口,如下图:
属性
- 行为:
- Filter:文件格式筛选器,如图片格式删选
JPEG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png|BMP Files (*.bmp)|*.bmp|All files (*.*)|*.*
- Filter:文件格式筛选器,如图片格式删选
24 颜色对话框colorDialog
25 数字选择器NumericUpDown
用于通过加减选择特定数字,如下图:
*. 常见异常
*.1 控件对应动作不响应
- 常识从该控件对应的事件属性中双击创建新的函数,再往该函数填充功能代码。