C# windows form 在控件事件触发迴圈 为何不会更新UI

一般在写 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 中间的数字完全没出现
http://img2.58codes.com/2024/20129372IUAdmQ5nym.png

如果希望迴圈在跑的过程 就更新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


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章