elowell elowell - 2 months ago 15
C# Question

How can you make a label fade in and out using timers in C#?

I am trying to use two timers to emulate the fading of a label on my form. Once the color values reach 255 in the first timer, the second timer is activated to reverse what the first timer did and bring the color values back to 0. When debugging, it works as expected for two 1 and a half rounds and then gives the error that the value has exceeded 255. This is because after going: timer1>timer2>timer1, it doesn't go to timer2, so the values keep increasing. What could be the issue?

This is in public Form1():

timer1.Tick += new EventHandler(timer1_Tick);
timer2.Tick += new EventHandler(timer2_Tick);


And here's the rest:

Timer timer1 = new Timer();
Timer timer2 = new Timer();
int r = 0;
int g = 0;
int b = 0;
int fade = 0;

private void timer1_Tick(object sender, EventArgs e)
{
fade++;
if (fade <= 500) //just a number above 255
{
r++;
g++;
b++;
lblReboot.ForeColor = Color.FromArgb(255, r, g, b);

if (r == 255)
{
fade = 0;
r = 255;
g = 255;
b = 255;
timer1.Stop();
timer1.Enabled = false;
timer2.Enabled = true;
timer2.Interval = 10;
timer2.Start();
}
}
}

private void timer2_Tick(object sender, EventArgs e)
{
fade++;
if (fade <= 500)
{
r--;
g--;
b--;
lblReboot.ForeColor = Color.FromArgb(255, r, g, b);
}

if (r == 0)
{
fade = 0;
r = 0;
g = 0;
b = 0;
timer2.Stop();
timer2.Enabled = false;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Enabled = true;
timer1.Interval = 10;
timer1.Start();
}
}

Answer

This is because you add multiple timer1.Tick event handlers when you change direction in the timer2_Tick. When you reach r == 255 in the second pass through - although you stop timer1 & start timer2 you still have another click event waiting to be processed which will increment the count to 256.

Remove this line

timer1.Tick += new EventHandler(timer1_Tick);

from timer2_Tick.

Comments