-
Notifications
You must be signed in to change notification settings - Fork 12
/
CountdownTimer.cs
68 lines (64 loc) · 2.2 KB
/
CountdownTimer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
namespace UniversaLIS
{
public class CountdownTimer
{
public CountdownTimer(int Duration)
{
duration = Duration;
RemainingDuration = duration;
timer.AutoReset = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(Count_down);
timer.Start();
}
public CountdownTimer(int Duration, EventHandler handler)
{
duration = Duration;
RemainingDuration = duration;
timer.AutoReset = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(Count_down);
timer.Start();
if (handler != null)
{
Timeout += handler;
}
}
public void Reset()
{
timer.Stop();
RemainingDuration = duration;
timer.Start();
}
public void Reset(int NewDuration)
{
duration = NewDuration;
RemainingDuration = duration;
}
private int duration;
public int RemainingDuration { get; set; }
private readonly System.Timers.Timer timer = new System.Timers.Timer(1000);
public event EventHandler? Timeout;
public void OnTimeout()
{
Timeout?.Invoke(this, EventArgs.Empty);
}
private void Count_down(object sender, EventArgs e)
{
/* If the countdown hits 0, trigger the Timeout event.
* If the timer hasn't expired, decrement remaining duration.
* Handling only these two conditions allows us to leave the timer running.
* That means we can use the Reset function whenever we want
* to set the timer without having to worry about starting it again.
*/
if (RemainingDuration == 0)
{
RemainingDuration--;
OnTimeout();
}
else if (RemainingDuration > 0)
{
RemainingDuration--;
}
}
}
}