标签随着计时器闪烁 [英] Label flashing with timers
问题描述
我正在尝试使几个标签在单击按钮时闪烁.使用当前代码,第一次单击可以正常工作,之后的每次单击只进行应有的闪烁次数的一半(变为白色,然后变为黑色).关于如何改善/解决此问题的任何想法?这是我当前的代码:
I'm trying to get a couple labels to flash on a button click. With the current code, the first click works properly, and each click afterwards only does half the amount of blinking it should (to white and back to black). Any ideas on how to improve/fix this? Here's my current code:
private int counter;
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
private void button1_Click_2(object sender, EventArgs e)
{
//Labels start out black, then play a sequence
//of changing to white and back to black twice
lb1.BackColor = Color.White;
lb2.BackColor = Color.White;
counter = 0;
timer.Interval = 300;
timer.Tick += new EventHandler(TimerElapsed);
timer.Enabled = true;
timer.Start();
}
void TimerElapsed(object sender, EventArgs e)
{
if (counter ==2)
{
timer.Stop();
timer.Enabled = false;
counter = 0;
}
else
{
if (lb2.BackColor == Color.Black)
{
lb1.BackColor = Color.White;
lb2.BackColor = Color.White;
}
else
{
lb1.BackColor = Color.Black;
lb2.BackColor = Color.Black;
}
counter += 1;
}
}
推荐答案
您要在每次单击按钮时将事件处理程序添加到Timer.Tick
.
You are adding an event handler to Timer.Tick
on each button click.
尝试将timer.Tick += new EventHandler(TimerElapsed);
行移出button1_Click_2
函数.
当您调用timer.Tick += new EventHandler(TimerElapsed);
时,将为Tick
事件添加另一个处理程序.当您单击该按钮时,它会引发多个TimerElapsed
,这会导致问题.通过将timer.Tick += new EventHandler(TimerElapsed);
移动到button1_Click_2
函数之外,您只需将TimerElapsed
分配给事件一次.
when you call timer.Tick += new EventHandler(TimerElapsed);
another handler will be added for Tick
event. It causes multiple TimerElapsed
to be fired when you click on the button and this cause the problem. By moving timer.Tick += new EventHandler(TimerElapsed);
outside the button1_Click_2
function you just assign TimerElapsed
to event once.
这篇关于标签随着计时器闪烁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!