I’m trying to animate a label while a process is ongoing. I want it to be something like this (frame by frame):
Searching
Searching.
Searching..
Searching...
Searching
and so on. I’ve tried to do it this way:
Timer _animationTimer = new Timer();
private void StartAnimation()
{
myLabel.Text = "Searching";
_animationTimer.Interval = 250;
_animationTimer.Tick += new EventHandler(this.AnimationEvent);
_animationTimer.Start();
}
private void StopAnimation()
{
_animationTimer.Stop();
}
private void AnimationEvent(object sender, EventArgs e)
{
if (!myLabel.Text.EndsWith("..."))
{
myLabel.Text += ".";
}
else
{
myLabel.Text = "Searching";
}
}
I use it this way:
StartAnimation();
// ... do something.
StopAnimation();
myLabel.Text = "Something";
But it doesn’t work. The first time it runs, it animates perfectly. The second time it shows this:
Searching..
Searching
Searching..
Searching
and the third time it shows:
Searching...
Searching..
Searching.
Searching
Searching...
and the fourth time it doesn’t animate at all. And from the fifth time and on it goes through this cycle.
It is really intriguing me. What can be wrong?
Your
StartAnimation()is adding the event handler each time you start. This is going to cause the problems you’re seeing.The second time you call
StartAnimation()you’ll have two event handlers wired up to the Tick event. It will call your code twice every 250 seconds instead of once. So you see patternThe third time there are three event handlers and you get the pattern
And so on. The fourth time nothing happens because it’s doing it four times and returning to the original state.
You can move the
line outside of the StartAnimation – or check that it’s null and only add it the first time.