Monday, February 23, 2009

Progress bar in windows applications .NET.

.NET frame work supports few classes that help to place Progress bar in User Interface of windows applications.




I am creating a windows form that displays this progress bar.
User interface (Windows form) :




Code :










using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace DeleteSvn
{
public partial class frmPrgs : Form
{
public frmPrgs()
{
InitializeComponent();
}

private void btnStart_Click(object sender, EventArgs e)
{
//Get input counter value
intCounter = Convert.ToInt32(txtTime.Text);
//set this counter value as maximum value for the progress bae
prg.Maximum = intCounter;
//start a thread that sleeps for every 1 second and updates the progress bar
//to next step after each second
Thread objThread = new Thread(this.RunThread);
//start the thread
objThread.Start();
}
int intCounter = 0;
delegate void UpdPrcs(string strStatusint,int intStep);
private void UpdateProcess(string strStatus, int prcStep)
{
if (InvokeRequired)
{
BeginInvoke(new UpdPrcs(this.UpdateProcess), new object[] { strStatus,prcStep});
return;
}
//Updating the components available in wodnows form from the thread
prg.Value=prcStep;
lblStaus.Text = "Status : " + strStatus;
if (prcStep == intCounter)
{
prg.Value = 0;
lblStaus.Text = "Done!";
MessageBox.Show("Done!");
}
}
private void RunThread()
{
int i = 0;
//increment counter and update UI with the status of counter and progress bar
while (i < intCounter)
{
i++;
UpdateProcess(i + " / " + intCounter, i);
Thread.Sleep(1000);
}

}
}
}
Output:-

When I click on start button after giving value as 10,
So it increments progress bar for each second and when time reaches 10 seconds progress bar is done with 100% and displays message box.










No comments: