1. 程式人生 > >C#winform使用進度條

C#winform使用進度條

在用c#做WinFrom開發的過程中。我們經常需要用到進度條(ProgressBar)用於顯示進度資訊。這時候我們可能就需要用到多執行緒,如果不採用多執行緒控制進度條,視窗很容易假死(無法適時看到進度資訊)。下面我就簡單結合一個我寫的例子給大家做一個介紹。
第一步:設計介面不說了...注意需要引用 using System.Threading;
第二步:定義一個代理,用於更新ProgressBar的值(Value)
//更新進度列表
private delegate void SetPos(int ipos);
第三步:進度條值更新函式(引數必須跟宣告的代理引數一樣)
private void SetTextMessage(int ipos)
{
if (this.InvokeRequired)
{
SetPos setpos = new SetPos(SetTextMessage);
this.Invoke(setpos, newobject[] { ipos});
}
else
{
this.label1.Text = ipos.ToString() + "/100";
this.progressBar1.Value = Convert.ToInt32(ipos);
}
}
第四步:函式實現
privatevoid button1_Click(object sender, EventArgs e)
{
Thread fThread = new Thread(new ThreadStart(SleepT));//開闢一個新的執行緒
fThread.Start();
}
第五步:新的執行緒執行函式:
privatevoid SleepT()
{
for (int i = 0; i < 500; i++)
{
System.Threading.Thread.Sleep(100);//沒什麼意思,單純的執行延時
SetTextMessage(100 * i / 500);
}
}
=============================
使用浮動進度條
1.浮動視窗
/// <summary>
/// Increase process bar
/// </summary>
/// <param name="nValue">the value increased</param>
/// <returns></returns>
public bool Increase(int nValue)
{
if (nValue > 0)
{
if (prcBar.Value + nValue < prcBar.Maximum)
{
prcBar.Value += nValue;
return true;
}
else
{
prcBar.Value = prcBar.Maximum;
this.Close();
return false;
}
}
return false;
}

2.使用進度的視窗
using System.Threading;
private frmProcessBar myProcessBar = null;
private delegate bool IncreaseHandle(int nValue);
private IncreaseHandle myIncrease = null;

private void ShowProcessBar()
{
myProcessBar = new frmProcessBar();
// Init increase event
myIncrease = new IncreaseHandle(myProcessBar.Increase);
myProcessBar.StartPosition = FormStartPosition.CenterScreen;
myProcessBar.ShowDialog();
myProcessBar = null;
}
private void ThreadFun()
{
MethodInvoker mi = new MethodInvoker(ShowProcessBar);
this.BeginInvoke(mi);
Thread.Sleep(1000);//Sleep a while to show window
bool blnIncreased = false;
object objReturn = null;
do
{
Thread.Sleep(50);
objReturn = this.Invoke(this.myIncrease, new object[] { 2 });
blnIncreased = (bool)objReturn;
}
while (blnIncreased);
}

使用方法:
Thread thdSub = new Thread(new ThreadStart(ThreadFun));
thdSub.Start();