具体
- 交通模拟界面设计
- 模拟时钟控件 (死循环 + 睡眠)
- 控件界面刷新技巧
- 线程解决GUI控件卡顿问题
- 异常捕捉的解决方法
- …
知识要点
- 掌握backgroundworker的使用
- 掌握sleep方法暂停线程
- 掌握不invoke的方法 解决不同线程得控件调用
- 界面刷新 使用Update方法 显示使用Show方法
- 掌握 try … catch 捕捉异常 处理异常
控件界面刷新技巧
- 解决在form 窗体上无法绘制的问题 使用 Show() 方法
- 解决绘制的持续性 使用重写事件 onPaint() 重写事件需要使用 override 关键字
窗体自带一个onPaint()事件,当窗体需要绘制时,自动调用该事件。
模拟时钟控件 (死循环 + 睡眠)
- 倒计时采用 while 循环
- for一般用在明确循环次数的时候
线程解决GUI控件卡顿问题
- 使用后台线程控制计算 backgroudWorker控件 ==> DoWork()事件
- backgroundWorker1.RunWorkerAsync(); //开启线程
异常捕捉的解决方法
1.System.InvalidOperationException:“线程间操作无效: 从不是创建控件“label2”的线程访问它。”
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
count--;
//利用委托进行线程间的调用
Invoke(new Action(() =>
{
label2.Text = count.ToString();
//停留1秒
Update();//刷新界面
}));
//第二种写法
//Invoke(new EventHandler(delegate
//{
// label2.Text = count.ToString();
// //停留1秒
// Update();//刷新界面
//}));
System.Threading.Thread.Sleep(1000);
}
}
开启双缓冲
//开启双缓冲 防止闪烁
this.SetStyle(ControlStylOptimizedDoubleBuffer,true);
this.SetStyle(ControlStyles.AllPaintingInWmPaitrue);
this.SetStyle(ControlStyles.ResizeRedraw,true);
this.SetStyle(ControlStyles.UserPaint,true);
抗锯齿
//抗锯齿
g.SmoothingMode = System.Drawing.Drawing2SmoothingMode.AntiAlias;