Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# 进度条

作者:刎心封爱为伱锁情   发布日期:2025-04-29   浏览:18

using System;
using System.Threading;
using System.Windows.Forms;

namespace ProgressBarExample
{
    public class Form1 : Form
    {
        private ProgressBar progressBar1;
        private Button startButton;

        public Form1()
        {
            // 初始化进度条和按钮
            progressBar1 = new ProgressBar();
            startButton = new Button();

            // 设置进度条的属性
            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;
            progressBar1.Value = 0;
            progressBar1.Step = 1;

            // 设置按钮的属性并添加点击事件
            startButton.Text = "Start";
            startButton.Click += new EventHandler(StartButton_Click);

            // 将控件添加到窗体中
            this.Controls.Add(progressBar1);
            this.Controls.Add(startButton);
        }

        private void StartButton_Click(object sender, EventArgs e)
        {
            // 创建一个新线程来模拟长时间运行的任务
            Thread thread = new Thread(new ThreadStart(RunLongTask));
            thread.Start();
        }

        private void RunLongTask()
        {
            for (int i = 0; i <= 100; i++)
            {
                // 更新进度条的值
                if (progressBar1.InvokeRequired)
                {
                    progressBar1.Invoke(new Action(() => progressBar1.Value = i));
                }
                else
                {
                    progressBar1.Value = i;
                }

                // 模拟任务处理时间
                Thread.Sleep(50);
            }
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

解释说明:

  1. 窗体和控件初始化:创建了一个 Form,并在其中添加了一个 ProgressBar 和一个 Button
  2. 进度条属性设置:设置了进度条的最小值、最大值、初始值和步长。
  3. 按钮点击事件:为按钮添加了点击事件,当按钮被点击时,启动一个新的线程来模拟长时间运行的任务。
  4. 多线程处理:使用 Thread 来模拟长时间运行的任务,并通过 Invoke 方法更新 UI 线程中的进度条值。
  5. 主程序入口:在 Main 方法中启动应用程序。

这个示例展示了如何在 C# WinForms 应用程序中使用进度条,并通过多线程技术确保 UI 的响应性。

上一篇:c# cancellationtokensource

下一篇:c# 位运算

大家都在看

c# 二进制

c# tcp client

c# type.gettype

c# sqlconnection

.net和c#

c#游戏开发

c#网络编程

c# rectangle

c# if else

c# rtsp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站