I have a C# program in which, I need the timer to stop if the user stops interacting with the program. What It needs to do is pause, and then restart when the user becomes active again. I have done some research, and found that there is commands such as:
timer.Stop();
and
timer.Start();
But I was wondering if there was like a:
timer.Pause();
And then when the user becomes active again, it picks up where it left off, and doesn't restart. If anyone can help, it would be much appreciated! Thanks,
Micah
You achieve this by using the Stopwatch
class in .NET. By simply stopping and starting you continue the use of the instance of the stopwatch.
Make sure to make use of using System.Diagnostics;
var timer = new Stopwatch();
timer.Start();
timer.Stop();
Console.WriteLine(timer.Elapsed);
timer.Start(); //Continues the timer from the previously stopped time
timer.Stop();
Console.WriteLine(timer.Elapsed);
To reset the stopwatch, just call the Reset
or Restart
methods, like below:
timer.Reset();
timer.Restart();
I have created this class for this situation:
public class PausableTimer : Timer
{
public double RemainingAfterPause { get; private set; }
private readonly Stopwatch _stopwatch;
private readonly double _initialInterval;
private bool _resumed;
public PausableTimer(double interval) : base(interval)
{
_initialInterval = interval;
Elapsed += OnElapsed;
_stopwatch = new Stopwatch();
}
public new void Start()
{
ResetStopwatch();
base.Start();
}
private void OnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
if (_resumed)
{
_resumed = false;
Stop();
Interval = _initialInterval;
Start();
}
ResetStopwatch();
}
private void ResetStopwatch()
{
_stopwatch.Reset();
_stopwatch.Start();
}
public void Pause()
{
Stop();
_stopwatch.Stop();
RemainingAfterPause = Interval - _stopwatch.Elapsed.TotalMilliseconds;
}
public void Resume()
{
_resumed = true;
Interval = RemainingAfterPause;
RemainingAfterPause = 0;
Start();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With