Label flashing with timers

依然范特西╮ 提交于 2020-01-25 00:06:25

问题


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

回答1:


You are adding an event handler to Timer.Tick on each button click.

Try moving the line timer.Tick += new EventHandler(TimerElapsed); out of button1_Click_2 function.

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.



来源:https://stackoverflow.com/questions/31127381/label-flashing-with-timers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!