Let’s implement a very simple Stopwatch Timer app today.
We will implement following features in our Stopwatch app :
1. Show Timer
2. Pause Timer
3. Stop / Reset Timer.
UI for our App :
1 2 3 4 5 6 7 8 9 10 |
<Grid> <StackPanel> <TextBlock HorizontalAlignment="Center" x:Name="StopwatchText" Text="0 : 0 : 0" FontSize="50" Foreground="White"/> <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> <Button x:Name="Start" Content="Start" Click="Start_Click"/> <Button x:Name="Pause" Content="Pause" Click="Pause_Click" Margin="5,0,0,0"/> <Button x:Name="Stop" Content="Stop" Click="Stop_Click" Margin="5,0,0,0" /> </StackPanel> </StackPanel> </Grid> |
So basically we have StackPanel that is Vertically arranged which contains a Textbox (To Display Timer) and another Horizontally arranged StackPanel (Containing Buttons).
For Timer we have used DispatchTimer,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#region Timer Methods private void StartTimer() { this.timer.Interval = new TimeSpan(0, 0, 1); this.timer.Tick += timer_Tick; this.timer.Start(); } private void StopTimer() { this.timer.Tick -= timer_Tick; this.timer.Stop(); } private void ResetTimer() { this.minutes = this.seconds = this.hours = 0; this.StopwatchText.Text = "0 : 0 : 0"; } #endregion |
In StartTimer method we are setting the interval for DispatchTimer to 1 sec. So it means that a Tick event will be raised every 1 sec.
we listen to that event in ,
this.timer.Tick += timer_Tick;
Whenever the timer.tick event is raised we change the time on UI using this simple logic ,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
private void timer_Tick(object sender, object e) { //Just change the text here ++this.seconds; if(this.seconds == 60) { this.minutes++; this.seconds = 0; } if(this.minutes == 60) { this.hours++; this.minutes = 0; } this.StopwatchText.Text = string.Format("{0} : {1} : {2}", hours,minutes, seconds); } |
This event is triggered every second , so increment second value every time this event is triggered.
Then check if 60 seconds, reset the seconds to zero and set minute++, similarly for minutes and hour.
And for button click events of Start, Pause , and Stop we will just call the Timer methods mentioned above in following manner :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
private void Start_Click(object sender, RoutedEventArgs e) { if(!this.timer.IsEnabled) { this.StartTimer(); } } private void Stop_Click(object sender, RoutedEventArgs e) { this.StopTimer(); this.ResetTimer(); } private void Pause_Click(object sender, RoutedEventArgs e) { if (this.timer.IsEnabled) { this.StopTimer(); } } |
Screen shot of Stopwatch Timer App :
you can download the full code here : Stopwatch.