我想用兩個計時器來模擬我的窗體上的標籤褪色。一旦第一個計時器中的顏色值達到255,第二個計時器將被激活,以反轉第一個計時器所做的操作,並將顏色值恢復爲0.調試時,按預期工作兩個半輪,然後給出錯誤,該值已超過255.這是因爲在執行後:timer1> timer2> timer1,它不會進入timer2,因此值不斷增加。可能是什麼問題?如何使用C#中的定時器使標籤淡入淡出?
這是公共Form1中():
timer1.Tick += new EventHandler(timer1_Tick);
timer2.Tick += new EventHandler(timer2_Tick);
而這裏的休息:
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();
}
}
你使用WPF嗎? – Roland