WinForm 学习总结 - 第二十三天
一、登录功能与窗体切换
1.1 应用程序入口
namespace _01_登录
{
internal static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LoginFrm loginFrm = new LoginFrm();
if (loginFrm.ShowDialog() == DialogResult.OK)
{
Application.Run(new BankCustormerFrm("admin"));
}
}
}
}
1.2 登录窗体实现
public partial class LoginFrm : Form
{
public LoginFrm()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
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 主窗体接收参数
public partial class BankCustormerFrm : Form
{
public BankCustormerFrm(string value)
{
InitializeComponent();
label1.Text = $"欢迎{value}进入";
}
}
二、模态对话框与非模态对话框
2.1 概念对比
| 特性 | 模态对话框 (ShowDialog()) | 非模态对话框 (Show()) |
|---|
| 窗口层级 | 独占顶层,阻止操作其他窗口 | 与主窗口平级,可自由切换 |
| 关闭方式 | Close() 关闭并销毁 | Hide() 隐藏(仍存在) |
| 返回值 | 返回 DialogResult | 无返回值 |
| 典型场景 | 登录框、确认框 | 工具栏、属性面板 |
2.2 关闭应用程序的方式
this.Close();
Application.Exit();
Application.ExitThread();
System.Environment.Exit(0);
推荐做法:在主窗体的 FormClosed 事件中使用:
private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
{
if (tip != null)
{
tip.Dispose();
}
Dispose();
System.Environment.Exit(0);
}
三、Controls 集合
3.1 遍历控件集合
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
foreach (Control c in Controls)
{
Console.WriteLine(c);
if (c is Button)
{
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 处理用户选择
DialogResult res = MessageBox.Show("确认删除吗", "删除", MessageBoxButtons.OKCancel);
if (res == DialogResult.OK)
{
Controls.Remove(label1);
}
五、RadioButton 控件(单选框)
5.1 特性
- 互斥性:同一容器内只能选择一个
- Checked 属性:
true 表示选中,false 表示未选中 - CheckedChanged 事件:选中状态改变时触发
5.2 代码示例
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Panel p1 = new Panel();
p1.BackColor = Color.Red;
p1.Size = new Size(100, 100);
p1.Location = new Point(330, 0);
RadioButton r1 = new RadioButton();
r1.Text = "男";
r1.Location = new Point(30, 10);
p1.Controls.Add(r1);
RadioButton r2 = new RadioButton();
r2.Text = "女";
r2.Location = new Point(30, 30);
r2.Checked = true;
p1.Controls.Add(r2);
r1.CheckedChanged += Fanfan;
r2.CheckedChanged += Fanfan;
this.Controls.Add(p1);
}
public void Fanfan(object o, EventArgs e)
{
RadioButton r = o as RadioButton;
if (r.Checked)
{
Console.WriteLine("选择了" + r.Text);
}
}
}
5.3 关键要点
- 互斥性:同一容器内的 RadioButton 自动互斥
- 分组:不同容器(Panel/GroupBox)中的 RadioButton 互不影响
- 事件:
CheckedChanged 在选中状态改变时触发
六、CheckBox 控件(复选框)
6.1 特性
- 独立选择:每个 CheckBox 独立,不互斥
- Checked 属性:
true 表示勾选,false 表示未勾选 - CheckedChanged 事件:勾选状态改变时触发
6.2 代码示例
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CheckBox c1 = new CheckBox()
{
Text = "new出来的多选框",
Location = new Point(180, 100),
Checked = true,
};
Controls.Add(c1);
checkBox2.CheckedChanged += checkBox1_CheckedChanged;
checkBox3.CheckedChanged += checkBox1_CheckedChanged;
c1.CheckedChanged += checkBox1_CheckedChanged;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender;
if (c.Checked)
{
Console.WriteLine(c.Text);
}
}
}
七、ListBox 控件(列表框)
7.1 选择模式
| SelectionMode | 说明 |
|---|
None | 不可选择 |
One | 单选(默认) |
MultiSimple | 多选(点击切换) |
MultiExtended | 多选(支持 Ctrl/Shift) |
7.2 代码示例
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listBox1.Items.Add("罗志祥");
listBox1.Items.Add("李云迪");
listBox1.Items.Add("蔡徐坤");
ListBox listBox = new ListBox();
listBox.Location = new Point(100, 20);
listBox.Size = new Size(100, 180);
Controls.Add(listBox);
string[] strings = new string[] { "111", "222", "333" };
listBox.Items.AddRange(strings);
listBox.SelectionMode = SelectionMode.MultiSimple;
listBox.SelectedIndexChanged += Xuanzhong;
}
public static void Xuanzhong(object sender, EventArgs e)
{
ListBox l1 = sender as ListBox;
string ss = string.Empty;
foreach (var item in l1.SelectedItems)
{
ss += item;
}
Console.WriteLine(ss);
}
}
八、ComboBox 控件(下拉框)
8.1 特性
- 结合文本框和列表框功能
- 支持输入和选择
DropDownStyle 属性控制行为
8.2 代码示例
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
ComboBox cb = new ComboBox();
cb.Size = new Size(60, 30);
cb.Location = new Point(100, 100);
Controls.Add(cb);
cb.Items.AddRange(new string[] { "吴亦凡", "罗志祥" });
cb.SelectedIndexChanged += Gaibian;
}
public static void Gaibian(object sender, EventArgs e)
{
ComboBox cb = sender as ComboBox;
Console.WriteLine(cb.SelectedItem);
Console.WriteLine(cb.SelectedIndex);
}
}
九、NumericUpDown 控件(数字输入框)
9.1 主要属性
| 属性 | 说明 |
|---|
Value | 当前数值(decimal 类型) |
Minimum | 最小值 |
Maximum | 最大值 |
Increment | 增减步长 |
DecimalPlaces | 小数位数 |
ThousandsSeparator | 是否显示千位分隔符 |
9.2 代码示例
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
NumericUpDown num = new NumericUpDown();
num.Value = 10;
num.Minimum = 0;
num.Maximum = 100;
num.Increment = 2;
num.DecimalPlaces = 0;
Controls.Add(num);
num.ValueChanged += new EventHandler(numValueChanged);
}
private void numValueChanged(object sender, EventArgs e)
{
NumericUpDown num = (NumericUpDown)sender;
MessageBox.Show("当前的值是: " + num.Value.ToString());
}
}
十、PictureBox 控件(图片框)
10.1 图片加载方式
pictureBox.Image = Image.FromFile(@"C:\Images\0001.PNG");
pictureBox.ImageLocation = @"C:\Images\0001.PNG";
pictureBox.Image = Properties.Resources.background;
10.2 SizeMode 属性
| SizeMode | 说明 |
|---|
Normal | 图片位于左上角,超出部分被剪切 |
StretchImage | 拉伸图片以适应控件(可能失真) |
Zoom | 保持比例缩放,完整显示 |
AutoSize | 控件根据图片自动调整大小 |
CenterImage | 图片居中显示,超出部分被剪切 |
10.3 代码示例
pictureBox1.Size = new Size(200, 150);
pictureBox1.Location = new Point(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 轮播图示例
public partial class Form1 : Form
{
int index = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
pictureBox1.Image = imageList1.Images[index];
}
private void button1_Click(object sender, EventArgs e)
{
index++;
if (index >= imageList1.Images.Count)
{
index = 0;
}
pictureBox1.Image = imageList1.Images[index];
}
}
十二、核心概念总结
12.1 窗体生命周期
构造函数 → Load事件 → 显示 → 用户交互 → FormClosing → 关闭
12.2 事件处理模式
private void button1_Click(object sender, EventArgs e) { }
btn.Click += (sender, e) => { MessageBox.Show("点击"); };
btn.Click += button1_Click;
btn.Click -= button1_Click;
12.3 控件创建方式
Control control = new ControlType();
control.Property = value;
this.Controls.Add(control);
十三、实用技巧
- 控件访问:通过
Name 属性或 Controls 集合访问控件 - 类型转换:使用
as 关键字安全转换 sender 对象 - 资源管理:使用
Properties.Resources 管理项目资源 - 线程安全:UI 更新应在 UI 线程执行,使用
Control.Invoke - 内存优化:使用
ImageList 共享图像资源
十四、使用场景
- 模态对话框用于需要用户确认的操作(如登录、确认删除)
- 非模态对话框用于辅助功能(如工具栏、搜索框)
- Controls 集合用于批量操作或动态控件管理
- 消息提示应适度使用,避免频繁弹窗影响用户体验
- 单选框分组使用
Panel 或 GroupBox 容器 - 图片显示根据需求选择合适的
SizeMode