如何衡量按钮点击之间的时间? C#

时间:2016-09-20 11:16:48

标签: c# button measure

我如何测量点击之间的时间,如果按钮点击之间的时间让我们说> = 1000毫秒(1秒)发生了某些事情,例如。 Msgbox弹出。

private void button1_Click(object sender, EventArgs e)
{
    Stopwatch sw = new Stopwatch();
    double duration = sw.ElapsedMilliseconds;
    double tt = 2000;

    sw.Start();

    if (duration >= tt)
    {
        textBox1.Text = "Speed reached!";
    }
    else
    {
        sw.Stop();
        duration = 0;
    }
}

2 个答案:

答案 0 :(得分:1)

你可以这样做:

  • 首次点击启动计时器,时间间隔为1000毫秒
  • 在第二次单击时停止计时器,或将其重置为零

如果计时器完成而没有中断,则其事件处理程序将显示消息框。

答案 1 :(得分:0)

由于您已经专门尝试使用Stopwatch类进行编码,因此我将提供使用该解决方案的解决方案。

您尝试的问题是您需要将Stopwatch实例声明为全局变量,这样您就可以在不同的点击事件中访问同一个实例。

Stopwatch sw = new Stopwatch();

private void button1_Click(object sender, EventArgs e)
{
    // First we need to know if it's the first click or the second.
    // We can do this by checking if the timer is running (i.e. starts on first click, stops on second.
    if(sw.IsRunning) // Is running, second click.
    {
        // Stop the timer and compare the elapsed time.
        sw.Stop();
        if(sw.ElapsedMilliseconds > 1000)
        {
            textBox1.Text = "Speed reached!";
        }
    }
    else // Not running, first click.
    {
        // Start the timer from 0.
        sw.Restart();
    }
}
相关问题