C# 设置下载进度条

该博客展示了如何使用C#编程实现一个模拟下载进度条的功能。通过创建线程、设置开始和结束值,更新进度条、显示当前值及百分比,实现了动态更新进度的效果。代码中使用了Windows Forms的ProgressBar控件,以及线程同步的相关技巧。
摘要由CSDN通过智能技术生成

C# 模拟下载进度条:

提示:
设置:开始值
设置:结束值


全部代码:

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 进度条
{
    public partial class Form1 : Form
    {
        private int start;
        private int end;
        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//设置该属性 为false
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)//开始下载按键
        {
            //创建线程,并创建ThreadStart委托对象
            Console.WriteLine("开始下载");
            Thread process = new Thread(PortScan);
            process.Start();

            start = Int32.Parse(textBox1.Text);//设置起始值
            end = Int32.Parse(textBox2.Text);//设置结束值

            progressBar1.Minimum = start;
            progressBar1.Maximum = end;
        }

        private void PortScan()
        {
            if(start<end)//开始值<结束值才符合逻辑
            {
                 for (int i = start; i <= end; i++)
                {
                    progressBar1.Value = i;//进度条
                    textBox3.Text = i.ToString();//当前值
                    System.Threading.Thread.Sleep(100);//延时
                    label4.Text = ((float)i / (end - start) * 100).ToString("n2") + "%";//计算百分比(保留2位小数)
                }
                Console.WriteLine("结束下载");
            }
        }
    }
}

效果

效果

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值