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("结束下载");
}
}
}
}