一.新建窗体类 progressBar_windows1.cs,窗体增加progressBar 和label1。progressBar_windows1.cs内容如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test.CentreWin
{
public partial class progressBar_windows1 : Form
{
public progressBar_windows1(int _Minimum, int _Maximum)//带参数,表示进度条的范围的最小值和最大值
{
InitializeComponent();
progressBar1.Maximum = _Maximum;//设置范围最大值
progressBar1.Value = progressBar1.Minimum = _Minimum;//设置范围最小值
}
public void setPos(int value)//设置进度条当前进度值
{
if (value <= progressBar1.Maximum)//如果值有效
{
progressBar1.Value = value;//设置进度值
label1.Text = (value * 100 / progressBar1.Maximum).ToString() + “%”;//显示百分比
}
Application.DoEvents();//重点,必须加上,否则父子窗体都假死
}
private void progressBar_windows1_Load(object sender, EventArgs e)
{
this.Owner.Enabled = false;//设置父窗体不可用
}
private void progressBar_windows1_FormClosed(object sender, FormClosedEventArgs e)
{
this.Owner.Enabled = true;//回复父窗体为可用
}
private void progressBar_windows_Shown(object sender, EventArgs e)
{
}
}
}
二.测试进度条
Int32 Coun = 100;
Int32 progressBar_Cnt2 = 0;
Int32 progressBar_all2 = 0;
progressBar_windows1 form2;// 显示进度条窗体
progressBar_Cnt2 = 0;
progressBar_all2 = 0;
progressBar_all2 = Coun ;
if (progressBar_all2 > 0)
{
form2 = new progressBar_windows1(0, progressBar_all2);
form2.Show(this);//设置父窗体
for(int i=0;i<Coun;i++)
{
/
//这里增加用户处理的内容
/
progressBar2_updata()
}
}
public void progressBar2_updata()
{
if (progressBar_all2 > 0)
{
progressBar_Cnt2++;
form2.setPos(progressBar_Cnt2);//设置进度条位置
if (progressBar_Cnt2 >= progressBar_all2)
{
form2.Close();
}
}
}