using System;
using System.Threading;
using System.Windows.Forms;
namespace ProgressBarExample
{
public partial class Form1 : Form
{
private ProgressBar progressBar1;
private Button startButton;
public Form1()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.progressBar1 = new ProgressBar();
this.startButton = new Button();
this.SuspendLayout();
// progressBar1
this.progressBar1.Location = new System.Drawing.Point(12, 12);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(260, 23);
this.progressBar1.TabIndex = 0;
// startButton
this.startButton.Location = new System.Drawing.Point(12, 41);
this.startButton.Name = "startButton";
this.startButton.Size = new System.Drawing.Size(75, 23);
this.startButton.TabIndex = 1;
this.startButton.Text = "Start";
this.startButton.UseVisualStyleBackColor = true;
this.startButton.Click += new EventHandler(this.StartButton_Click);
// Form1
this.ClientSize = new System.Drawing.Size(284, 76);
this.Controls.Add(this.startButton);
this.Controls.Add(this.progressBar1);
this.Name = "Form1";
this.Text = "ProgressBar Example";
this.ResumeLayout(false);
}
private void StartButton_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(RunProgress));
thread.Start();
}
private void RunProgress()
{
for (int i = 0; i <= 100; i++)
{
if (this.progressBar1.InvokeRequired)
{
this.progressBar1.Invoke((MethodInvoker)delegate
{
this.progressBar1.Value = i;
});
}
else
{
this.progressBar1.Value = i;
}
Thread.Sleep(50); // Simulate some work being done
}
}
}
}
ProgressBar 和 Button 的窗体。Invoke 方法确保 UI 线程安全地更新进度条。Thread.Sleep 模拟一些工作,使进度条的更新看起来更平滑。这个示例展示了如何在 C# WinForms 应用程序中使用 ProgressBar 控件,并确保在多线程环境中正确更新 UI。
上一篇:c#连接oracle数据库
下一篇:c# eventhandler
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站