using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace 进度条测试
{
//需要一个委托
public delegate void SetPos(int iPos);
public partial class MyProcessBar1 : Form
{
public MyProcessBar1()
{
InitializeComponent();
}
//然后是代码
private void button1_Click(object sender, EventArgs e)
{
Thread th = new Thread(new ThreadStart(ChangePosMethod));//新进程要用委托调用
th.Start();
}
/// <summary>
/// 进度条执行方法
/// </summary>
private void ChangePosMethod()
{
for (int i = 0; i < 1000; i++)
{
System.Threading.Thread.Sleep(1000);
ChangeText(i);
}
}
/// <summary>
/// 改变位置
/// </summary>
private void ChangeText(int pos)
{
if (this.InvokeRequired)//说明有一个创建它(UI进程)以外的线程想访问它,在这里应该是(线程ch)
{
SetPos sp = new SetPos(ChangeText);
this.Invoke(sp, pos);//找到UI进程,让它来调用这个方法
}
else
{
this.progressBar1.Value = Convert.ToInt32(pos);
}
}
}
}
然后我把它封装到一个类中直接可以使用:
使用方法:
int nowProcessNum = (k + 1) * this.progressBar1.Maximum / tableNames.Length;
Common.ProcessBarHelper.ChangeText(nowProcessNum, progressBar1);
Common.ProcessBarHelper.ChangeVisbleState(progressBar1);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Common
{
public delegate void SetPos(int iPos, ProgressBar progressBar1);
public delegate void SetState(ProgressBar progressBar1);
public static class ProcessBarHelper
{
public static void ChangeText(int pos, ProgressBar progressBar1)
{
if (progressBar1.InvokeRequired)//说明有一个创建它(UI)以外的线程(我们创建的线程)想访问它
{
SetPos sp = new SetPos(ChangeText);
progressBar1.Invoke(sp, pos, progressBar1);//找到创建它的进程(UI进程)让它来调用这个方法
}
else
{
if (pos > progressBar1.Maximum)
{
pos = progressBar1.Maximum;
}
progressBar1.Value = Convert.ToInt32(pos);
}
}
public static void ChangeVisbleState(ProgressBar progressBar1)
{
if (progressBar1.InvokeRequired)//说明有一个创建它(UI)以外的线程(我们创建的线程)想访问它
{
SetState sp = new SetState(ChangeVisbleState);
progressBar1.Invoke(sp, progressBar1);//找到创建它的进程(UI进程)让它来调用这个方法
}
else
{
if (progressBar1.Visible == false)
{
progressBar1.Visible = true;
progressBar1.Value = 1;
}
else
{
progressBar1.Visible = false;
}
}
}
}
}