Search code examples
c#timerstopwatchmilliseconds

How do I measure time between clicks?


I've been making a small project for myself trying to measure time between 2 clicks. Later on I will change it to key presses but that I can do on my own. I need to measure the time in milliseconds and the only way I knew about was to use timer...

    bool clicked = true;
    int time = 0;

    private void button1_Click(object sender, EventArgs e)
    {
        if (clicked)
        {
            timer1.Start();
            clicked = false;
        }
        else
        {
            timer1.Stop();
            clicked = true;
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        time += 10;
        label1.Text = Convert.ToString(time);
    }

The timer is set with the interval of 10 ticks and just to visually see I also made the timer display the time. But when I was testing it, I added another timer with the interval of 1000 ticks and by that I saw the difference. I later on realized the timer is inaccurate. I started digging and the only thing that was being recommended was stopwatch and I tried this...

    private void button1_Click(object sender, EventArgs e)
    {
        var timer = new Stopwatch();

        if (clicked)
        {
            timer.Start();
            clicked = false;
        }
        else
        {
            timer.Stop();
            TimeSpan timeTaken = timer.Elapsed;
            label1.Text = timeTaken.ToString();
            clicked = true;
        }
    }

But that returns the result of "00:00:00" every time. What do I do?


Solution

  • I think you don't need a timer, you just have to compute the time elapsed between the first click (store the date and time it occured in the dtPreviousClick variable) and the second one. The difference between 2 DateTime objects is a Timespan objects which has a property named TotalMilliseconds which is the value you're looking for.

    Ref: https://learn.microsoft.com/en-us/dotnet/api/system.timespan.totalmilliseconds

    bool clicked = false;
    DateTime dtPreviousClick;
    
    private void button1_Click(object sender, EventArgs e)
    {
      if (!clicked)
      {
        dtPreviousClick = DateTime.UtcNow;
        clicked = true;
        label1.Text = "awaiting another click....";
        
      }
      else
      {
        label1.Text = (DateTime.UtcNow - dtPreviousClick).TotalMilliseconds.ToString();
        clicked = false;
      }
    }