c# - Checking the time difference between boolean values -
i've got boolean value called ispressed
active when keyboard , mouse buttons active. want achieve when ispressed
boolean value true
start timer (preferably using stopwatch class). while ispressed
true keep timer going , ispressed
false
stop timer , difference. after it's stopped , it's true again , stops again, add difference previous timer.
i tried use code post couldn't work. tried doing 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 stayed @ 0.
i'm thinking stopwatch maybe unnecessary overhead. mark time ispressed set true , time ispressed set false , calculation.
private long _pressedticks; private long _durationticks; private bool _pressed; public bool pressed { { 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; } } }
Comments
Post a Comment