WinForm 学习总结 - 第二十三天
一、登录功能与窗体切换
1.1 应用程序入口
namespace_01_登录{internalstaticclassProgram{[STAThread]staticvoidMain(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);LoginFrmloginFrm=newLoginFrm();// 使用 ShowDialog() 以模态方式显示登录窗体if(loginFrm.ShowDialog()==DialogResult.OK){// 登录成功后显示主窗体Application.Run(newBankCustormerFrm("admin"));}}}}
1.2 登录窗体实现
publicpartialclassLoginFrm:Form{publicLoginFrm(){InitializeComponent();}privatevoidbtnLogin_Click(objectsender,EventArgse){// 验证账号if(string.IsNullOrWhiteSpace(txtAccount.Text)){label3.Text="账号不能为空白!";return;}// 验证密码if(string.IsNullOrWhiteSpace(txtPassword.Text)){MessageBox.Show("密码不能为空白!");return;}// 验证账号密码if(!(txtAccount.Text=="admin"&&txtPassword.Text=="admin")){MessageBox.Show("账号或密码出错,请重新输入!");return;}// 登录成功,设置返回结果DialogResult=DialogResult.OK;}}
1.3 主窗体接收参数
publicpartialclassBankCustormerFrm:Form{publicBankCustormerFrm(stringvalue){InitializeComponent();label1.Text=$"欢迎{value}进入";}}
二、模态对话框与非模态对话框
2.1 概念对比
| 特性 | 模态对话框 (ShowDialog()) | 非模态对话框 (Show()) |
|---|
| 窗口层级 | 独占顶层,阻止操作其他窗口 | 与主窗口平级,可自由切换 |
| 关闭方式 | Close()关闭并销毁 | Hide()隐藏(仍存在) |
| 返回值 | 返回DialogResult | 无返回值 |
| 典型场景 | 登录框、确认框 | 工具栏、属性面板 |
2.2 关闭应用程序的方式
// 1. 关闭当前窗口(非主窗口无法退出程序)this.Close();// 2. 退出所有窗体(无法处理非托管线程)Application.Exit();// 3. 退出调用线程上的所有消息Application.ExitThread();// 4. 最彻底的退出方式(强制退出所有线程)System.Environment.Exit(0);
推荐做法:在主窗体的FormClosed事件中使用:
privatevoidfrmMain_FormClosed(objectsender,FormClosedEventArgse){if(tip!=null){tip.Dispose();}Dispose();System.Environment.Exit(0);}
三、Controls 集合
3.1 遍历控件集合
publicpartialclassForm1:Form{publicForm1(){InitializeComponent();// 遍历窗体上所有控件foreach(ControlcinControls){Console.WriteLine(c);// 筛选特定类型控件if(cisButton){Console.WriteLine(c.Text);}}// 通过索引访问控件Console.WriteLine(Controls[0]);Console.WriteLine(Controls[1]);}}
四、消息提示框 (MessageBox)
4.1 基本用法
// 基本消息提示MessageBox.Show("提示信息");// 带标题MessageBox.Show("提示信息","窗口标题");// 带按钮类型和图标MessageBox.Show("提示信息","窗口标题",MessageBoxButtons.YesNo,MessageBoxIcon.Stop,MessageBoxDefaultButton.Button2);
4.2 MessageBoxButtons 枚举
| 枚举值 | 按钮组合 |
|---|
OK | 确定 |
OKCancel | 确定、取消 |
YesNo | 是、否 |
YesNoCancel | 是、否、取消 |
RetryCancel | 重试、取消 |
AbortRetryIgnore | 中止、重试、忽略 |
4.3 MessageBoxIcon 枚举
| 枚举值 | 图标样式 |
|---|
Information | 信息图标 (i) |
Warning | 警告图标 (!) |
Error | 错误图标 (X) |
Question | 疑问图标 (?) |
Asterisk | 信息图标 |
Exclamation | 警告图标 |
Hand | 错误图标 |
Stop | 错误图标 |
4.4 处理用户选择
DialogResultres=MessageBox.Show("确认删除吗","删除",MessageBoxButtons.OKCancel);if(res==DialogResult.OK){// 用户点击确定Controls.Remove(label1);}
五、RadioButton 控件(单选框)
5.1 特性
- 互斥性:同一容器内只能选择一个
- Checked 属性:
true表示选中,false表示未选中 - CheckedChanged 事件:选中状态改变时触发
5.2 代码示例
publicpartialclassForm1:Form{publicForm1(){InitializeComponent();// 创建Panel作为容器Panelp1=newPanel();p1.BackColor=Color.Red;p1.Size=newSize(100,100);p1.Location=newPoint(330,0);// 创建单选框RadioButtonr1=newRadioButton();r1.Text="男";r1.Location=newPoint(30,10);p1.Controls.Add(r1);RadioButtonr2=newRadioButton();r2.Text="女";r2.Location=newPoint(30,30);r2.Checked=true;// 默认选中p1.Controls.Add(r2);// 添加事件处理r1.CheckedChanged+=Fanfan;r2.CheckedChanged+=Fanfan;this.Controls.Add(p1);}publicvoidFanfan(objecto,EventArgse){RadioButtonr=oasRadioButton;if(r.Checked){Console.WriteLine("选择了"+r.Text);}}}
5.3 关键要点
- 互斥性:同一容器内的 RadioButton 自动互斥
- 分组:不同容器(Panel/GroupBox)中的 RadioButton 互不影响
- 事件:
CheckedChanged在选中状态改变时触发
六、CheckBox 控件(复选框)
6.1 特性
- 独立选择:每个 CheckBox 独立,不互斥
- Checked 属性:
true表示勾选,false表示未勾选 - CheckedChanged 事件:勾选状态改变时触发
6.2 代码示例
publicpartialclassForm1:Form{publicForm1(){InitializeComponent();// 动态创建 CheckBoxCheckBoxc1=newCheckBox(){Text="new出来的多选框",Location=newPoint(180,100),Checked=true,// 默认勾选};Controls.Add(c1);// 绑定事件checkBox2.CheckedChanged+=checkBox1_CheckedChanged;checkBox3.CheckedChanged+=checkBox1_CheckedChanged;c1.CheckedChanged+=checkBox1_CheckedChanged;}privatevoidcheckBox1_CheckedChanged(objectsender,EventArgse){CheckBoxc=(CheckBox)sender;if(c.Checked){Console.WriteLine(c.Text);}}}
七、ListBox 控件(列表框)
7.1 选择模式
| SelectionMode | 说明 |
|---|
None | 不可选择 |
One | 单选(默认) |
MultiSimple | 多选(点击切换) |
MultiExtended | 多选(支持 Ctrl/Shift) |
7.2 代码示例
publicpartialclassForm1:Form{publicForm1(){InitializeComponent();// 添加项listBox1.Items.Add("罗志祥");listBox1.Items.Add("李云迪");listBox1.Items.Add("蔡徐坤");// 动态创建 ListBoxListBoxlistBox=newListBox();listBox.Location=newPoint(100,20);listBox.Size=newSize(100,180);Controls.Add(listBox);// 批量添加string[]strings=newstring[]{"111","222","333"};listBox.Items.AddRange(strings);// 设置多选模式listBox.SelectionMode=SelectionMode.MultiSimple;// 绑定事件listBox.SelectedIndexChanged+=Xuanzhong;}publicstaticvoidXuanzhong(objectsender,EventArgse){ListBoxl1=senderasListBox;// 单选:获取选中项// Console.WriteLine(l1.SelectedItem);// Console.WriteLine(l1.SelectedIndex);// 多选:遍历所有选中项stringss=string.Empty;foreach(variteminl1.SelectedItems){ss+=item;}Console.WriteLine(ss);}}
八、ComboBox 控件(下拉框)
8.1 特性
- 结合文本框和列表框功能
- 支持输入和选择
DropDownStyle属性控制行为
8.2 代码示例
publicpartialclassForm1:Form{publicForm1(){InitializeComponent();// 动态创建 ComboBoxComboBoxcb=newComboBox();cb.Size=newSize(60,30);cb.Location=newPoint(100,100);Controls.Add(cb);// 添加项cb.Items.AddRange(newstring[]{"吴亦凡","罗志祥"});// 绑定事件cb.SelectedIndexChanged+=Gaibian;}publicstaticvoidGaibian(objectsender,EventArgse){ComboBoxcb=senderasComboBox;Console.WriteLine(cb.SelectedItem);// 获取选中项Console.WriteLine(cb.SelectedIndex);// 获取选中索引}}
九、NumericUpDown 控件(数字输入框)
9.1 主要属性
| 属性 | 说明 |
|---|
Value | 当前数值(decimal 类型) |
Minimum | 最小值 |
Maximum | 最大值 |
Increment | 增减步长 |
DecimalPlaces | 小数位数 |
ThousandsSeparator | 是否显示千位分隔符 |
9.2 代码示例
publicpartialclassForm1:Form{publicForm1(){InitializeComponent();NumericUpDownnum=newNumericUpDown();num.Value=10;// 初始值num.Minimum=0;// 最小值num.Maximum=100;// 最大值num.Increment=2;// 步长num.DecimalPlaces=0;// 小数位数Controls.Add(num);// 绑定值改变事件num.ValueChanged+=newEventHandler(numValueChanged);}privatevoidnumValueChanged(objectsender,EventArgse){NumericUpDownnum=(NumericUpDown)sender;MessageBox.Show("当前的值是: "+num.Value.ToString());}}
十、PictureBox 控件(图片框)
10.1 图片加载方式
// 方式1:从文件加载pictureBox.Image=Image.FromFile(@"C:\Images\0001.PNG");// 方式2:设置图片路径pictureBox.ImageLocation=@"C:\Images\0001.PNG";// 方式3:从资源加载pictureBox.Image=Properties.Resources.background;
10.2 SizeMode 属性
| SizeMode | 说明 |
|---|
Normal | 图片位于左上角,超出部分被剪切 |
StretchImage | 拉伸图片以适应控件(可能失真) |
Zoom | 保持比例缩放,完整显示 |
AutoSize | 控件根据图片自动调整大小 |
CenterImage | 图片居中显示,超出部分被剪切 |
10.3 代码示例
pictureBox1.Size=newSize(200,150);pictureBox1.Location=newPoint(10,10);pictureBox1.SizeMode=PictureBoxSizeMode.StretchImage;pictureBox1.Image=Image.FromFile(@"C:\Images\0001.PNG");// 点击事件pictureBox1.Click+=(sender,e)=>{MessageBox.Show("图片被点击了!");};
十一、ImageList 组件
11.1 特性
- 存储和管理多个图像
- 供其他控件共享使用(如 ListView、TreeView)
- 减少内存占用
11.2 轮播图示例
publicpartialclassForm1:Form{intindex=0;publicForm1(){InitializeComponent();}privatevoidForm1_Load(objectsender,EventArgse){// 显示第一张图pictureBox1.Image=imageList1.Images[index];}privatevoidbutton1_Click(objectsender,EventArgse){// 切换到下一张index++;if(index>=imageList1.Images.Count){index=0;}pictureBox1.Image=imageList1.Images[index];}}
十二、核心概念总结
12.1 窗体生命周期
构造函数 → Load事件 → 显示 → 用户交互 → FormClosing → 关闭
12.2 事件处理模式
// 方式1:设计器绑定privatevoidbutton1_Click(objectsender,EventArgse){}// 方式2:代码绑定(Lambda)btn.Click+=(sender,e)=>{MessageBox.Show("点击");};// 方式3:代码绑定(方法引用)btn.Click+=button1_Click;// 移除事件btn.Click-=button1_Click;
12.3 控件创建方式
// 方式1:设计器拖放(可视化)// 方式2:代码动态创建Controlcontrol=newControlType();control.Property=value;this.Controls.Add(control);
十三、实用技巧
- 控件访问:通过
Name属性或Controls集合访问控件 - 类型转换:使用
as关键字安全转换sender对象 - 资源管理:使用
Properties.Resources管理项目资源 - 线程安全:UI 更新应在 UI 线程执行,使用
Control.Invoke - 内存优化:使用
ImageList共享图像资源
十四、使用场景
- 模态对话框用于需要用户确认的操作(如登录、确认删除)
- 非模态对话框用于辅助功能(如工具栏、搜索框)
- Controls 集合用于批量操作或动态控件管理
- 消息提示应适度使用,避免频繁弹窗影响用户体验
- 单选框分组使用
Panel或GroupBox容器 - 图片显示根据需求选择合适的
SizeMode