带定时器的标签闪烁
Label flashing with timers
我正在尝试让几个标签在单击按钮时闪烁。使用当前代码,第一次点击可以正常工作,之后的每次点击只会进行一半的闪烁(白色和黑色)。关于如何 improve/fix 有什么想法吗?这是我当前的代码:
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
添加一个事件处理程序。
尝试将行 timer.Tick += new EventHandler(TimerElapsed);
移出 button1_Click_2
函数。
当您调用 timer.Tick += new EventHandler(TimerElapsed);
时,将为 Tick
事件添加另一个处理程序。当您单击按钮时,它会导致多个 TimerElapsed
被触发,这会导致问题。通过将 timer.Tick += new EventHandler(TimerElapsed);
移动到 button1_Click_2
函数之外,您只需将 TimerElapsed
分配给事件一次。
我正在尝试让几个标签在单击按钮时闪烁。使用当前代码,第一次点击可以正常工作,之后的每次点击只会进行一半的闪烁(白色和黑色)。关于如何 improve/fix 有什么想法吗?这是我当前的代码:
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
添加一个事件处理程序。
尝试将行 timer.Tick += new EventHandler(TimerElapsed);
移出 button1_Click_2
函数。
当您调用 timer.Tick += new EventHandler(TimerElapsed);
时,将为 Tick
事件添加另一个处理程序。当您单击按钮时,它会导致多个 TimerElapsed
被触发,这会导致问题。通过将 timer.Tick += new EventHandler(TimerElapsed);
移动到 button1_Click_2
函数之外,您只需将 TimerElapsed
分配给事件一次。