Increase a ProgressBar with Timer in WinForms [closed]
I have a timer with an interval of 1 minute and I would like to increase a progress bar in parallel with it. I'm using Winforms and C#. How can 开发者_运维知识库I do this ?
Help me please
Here is an example of how to use the Timer
control with a progress bar. First, create a new Timer
and a ProgressBar
. then, start the time when the form is loaded, using this function:
timer1.Enabled = true; // Enable the timer.
timer1.Start();//Strart it
timer1.Interval = 1000; // The time per tick.
Then, create an event for the tick, as shown:
timer1.Tick += new EventHandler(timer1_Tick);
Create the event's function:
void timer1_Tick(object sender, EventArgs e)
{
throw new NotImplementedException();
}
After this, add code to the tick function that adds value to the progress bar, similar to this:
progressBar1.Value++;
Don't forget to set a maximum value for the progress bar, which you can do by adding this code to the form_load
function:
progressBar1.Maximum = 10; // 10 is an arbitrary maximum value for the progress bar.
Also, don't forget to check the maximum value so your timer will stop. You can stop the timer with this code:
timer1.Stop();
Full Code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Start();
timer1.Interval = 1000;
progressBar1.Maximum = 10;
timer1.Tick += new EventHandler(timer1_Tick);
}
void timer1_Tick(object sender, EventArgs e)
{
if (progressBar1.Value != 10)
{
progressBar1.Value++;
}
else
{
timer1.Stop();
}
}
}
精彩评论