标签与计时器闪烁(Label flashing with timers)

2019-10-23 13:35发布

我试图让一对夫妇的标签闪烁的按钮点击。 在当前的代码,第一次点击正常工作,而每次点击后只能做它应该闪烁(白色,背部为黑色)的一半。 关于如何提高任何想法/解决这一问题? 这里是我当前的代码:

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;
    }     
}

Answer 1:

你加入一个事件处理Timer.Tick上的每个按钮的点击。

尝试移动线timer.Tick += new EventHandler(TimerElapsed);button1_Click_2功能。

当你调用timer.Tick += new EventHandler(TimerElapsed); 另一个处理程序将被添加Tick事件。 这导致多个TimerElapsed当你点击该按钮,这导致该问题被解雇。 通过移动timer.Tick += new EventHandler(TimerElapsed);button1_Click_2功能,您只需指定TimerElapsed到事件一次。



文章来源: Label flashing with timers