用WinForm实现进度条显示
1. 整体UI
2. backgroundwork事件
它用于在单独的后台线程上执行耗时的操作,而不阻塞UI线程
创建backgroundwork
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26//------------------------backgroundworker_Dowork事件------------------------
//------------------------(object sender,EventArgs e)具体表示什么意思?------------------------
//Sender是事件源,表示触发事件的那个组件,比如按钮,标签,列表
//EventArgs是事件参数,是用来辅助处理事件的,比如用鼠标点击窗体,这个EventArgs就会包含点击的位置信息等相关细节信息
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//新线程,新任务
//as
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1;i<=100;i++)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;//更改运行返回状态,并不能取消停止
break;
}
else
{
//实际编码的时候,把此处替换为工作代码
Thread.Sleep(50);
//提交进度报告,非常重要的方法
worker.ReportProgress(i);
}
}
e.Result = e.Argument;
}事件启动和停止
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16//事件启动
private void button7_Click(object sender, EventArgs e)
{
if (backgroundWorker1.IsBusy != true)
{
backgroundWorker1.RunWorkerAsync("放入启动参数,其实也可以不放");
}
}
//事件停止
private void button8_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
backgroundWorker1.CancelAsync();
}
}进度条变化处理事件
1
2
3
4
5
6//进度条变化处理事件
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value=e.ProgressPercentage;
label2.Text= (e.ProgressPercentage.ToString() + "%");
}事件处理完成
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16//事件处理完成
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
label2.Text = "Canceled";
}
else if (e.Error != null)
{
label2.Text="Error"+e.Error.Message;
}
else
{
label2.Text = "Done!Result=" + e.Result;
}
}
用WinForm实现进度条显示
http://example.com/2024/07/21/用WinForm实现进度条显示/