Label flashing with timers

2019-08-08 21:03发布

问题:

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.