-2

I've got a Boolean value called isPressed which is active when all keyboard and mouse buttons are active. What I want to achieve is when the isPressed Boolean value is true to start a timer (preferably using the Stopwatch class). While isPressed is true keep the timer going and as soon as isPressed is false then stop the timer and get the difference. After it's stopped and it's true again and then stops again, add the difference to the previous timer.

I tried to use the code from this post but I couldn't get it to work. I tried doing something like:

Stopwatch stopWatch = new Stopwatch();
TimeSpan ts = stopWatch.Elapsed;
if (isPressed)
{
    stopWatch.Start();
}
else
{
    stopWatch.Stop();
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
    lblTime.Text = string.Format("{0}", elapsedTime);
}

The lblTime label always stayed at 0.

Community
  • 1
  • 1
Zer0
  • 1,002
  • 1
  • 19
  • 40

2 Answers2

1

I'm thinking a stopwatch is maybe an unnecessary overhead. You could mark the time isPressed is set to true and the time isPressed is set to false and then do the calculation.

    private long _pressedTicks;
    private long _durationTicks;

    private bool _pressed;

    public bool Pressed
    {
        get { return _pressed; }
        set
        {
            if (value == _pressed)
            {
                //Do nothing;
            }
            else if (value == false)
            {
                _durationTicks = DateTime.Now.Ticks - _pressedTicks;
                _pressed = value;
            }
            else
            {
                _pressed = value;
                _pressedTicks = DateTime.Now.Ticks;
            }
        }
    }
RobCroll
  • 2,571
  • 1
  • 26
  • 36
  • Note: Call `Pressed = true` or `Pressed = false` as appropriate from your KeyDown and MouseDown event handlers. – Eric J. Sep 30 '15 at 00:20
0

I actually managed to get it to work thanks to @Andrey Nasonov, All I have to do was actually set Stopwatch stopWatch = new Stopwatch(); global.

Zer0
  • 1,002
  • 1
  • 19
  • 40