燃燃么 2014-11-16 07:07 采纳率: 0%
浏览 5788

C# Winform Timer倒计时问题

使用Timer控件做一个倒计时器
可以根据输入的值来控制倒计时的事件。

假设输入的是180s
第一次点开始按钮是 180 179 178 ......正常的
点了重置按钮之后,第二次点开始按钮就是 180 178 176.....
再次重置并且点击开始按钮之后,变成 180 177 174...
...
这些间隔都是1s

这是什么情况?如何解决?

以下为简化版的代码:

private void buttonSetTimeStart_Click(object sender, EventArgs e)
{
    this.Clock = 180;
    this.timerSetTime.Enabled = true;
    this.timerSetTime.Tick += new EventHandler(timerSetTime_Tick);
    this.timerSetTime.Start();
}

void timerSetTime_Tick(object sender, EventArgs e)
{
    Clock--;
    this.labelSetTimeMinute.Text = Clock.ToString();
    if (Clock == 0)
    {
        this.timerSetTime.Stop();
    }
}

private void buttonSetTimeReset_Click(object sender, EventArgs e)
{
    this.timerSetTime.Enabled = false;
    this.timerSetTime.Stop();
    this.timerSetTime.Interval = 1000;
    this.labelSetTimeMinute.Text = "";
}
  • 写回答

1条回答

  • threenewbee 2014-11-18 08:36
    关注

    问题在这里
    this.timerSetTime.Tick += new EventHandler(timerSetTime_Tick);
    你每次都挂接了一个新的事件处理程序
    导致它被重复执行了2次、3次。
    解决方法就是将这一行写在FormLoad中。

    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容