一般在写 windows form 程式时
如果不是大型开发
老闆只要求 东西能动 项目立刻好
我们可能就会把 逻辑写在控件事件内 像是
button1_Click(object sender, EventArgs e)
如果控件事件内塞了迴圈 迴圈内的又希望能更新UI显示的内容 如下写法会失败
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;namespace Control_Refresh_1{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { for (int i = 0; i < 11; i++) { Thread.Sleep(200); textBox1.Text = i.ToString(); } } }}
上面的例子 迴圈完全跑完才会显示10 中间的数字完全没出现
如果希望迴圈在跑的过程 就更新UI 就需要使用
Control.Refresh 方法
强制控制项使其工作区失效,并且立即重绘其本身和任何子控制项。
实际使用就是在对的地方加上
this.Refresh();
完整程式码如下
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows.Forms;namespace Control_Refresh_1{ public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { for (int i = 0; i < 11; i++) { Thread.Sleep(200); textBox1.Text = i.ToString(); this.Refresh(); } } }}
参考文章
https://www.ez2o.com/Blog/Post/csharp-Object-Refresh
https://www.cnblogs.com/aooyu/archive/2012/04/12/2444395.html