Playing With Timer - C# (WinStore, WinPhone)
This article will help you to add timer in your Windows Store or Phone app using C#.
Step # 1: Load/Open App project in Visual Studio.
Step # 2: Open MainPage.xaml (from solution explorer) and Add Following Elements to Grid:
<Grid>
<Button x:Name="start" Content="Start Timer" HorizontalAlignment="Left" Margin="269,43,0,0" VerticalAlignment="Top" Click="start_Click"/>
<Button x:Name="stop" Content="Stop Timer" HorizontalAlignment="Left" Margin="269,86,0,0" VerticalAlignment="Top"
Click="stop_Click"/>
<TextBlock x:Name="status" FontSize="24" HorizontalAlignment="Left" Margin="10,174,0,0" TextWrapping="Wrap"
VerticalAlignment="Top" Height="98" Width="380"/>
</Grid>
Explanation:
Added two button by name start and stop, and created click event for them.
Whenever "start" button will be clicked, Timer will start.
Whenever "stop" button will be clicked, Timer will stop.
Textblock by name "status" is used to inform user about time elapsed information.
Step # 3: Open MainPage.xaml.cs file (from solution explorer), and add following code, such that:
//No New Library file needed
public sealed partial class MainPage : Page
{
int elapsed_time;//used to store number of seconds elapsed
private DispatcherTimer timer;//declared timer object
public MainPage()//Constructor
{
elapsed_time = 0;//reset variable
this.InitializeComponent();//by default
status.Text = "Press Start Timer to Start Timer!";//status message displayed to user
}
private void start_Click(object sender, RoutedEventArgs e)//when start button is clicked
{
timer = new DispatcherTimer();//initialized timer as new object
timer.Interval = TimeSpan.FromSeconds(1);//Set time interval of 1 second
//You have option to set millisecond, hour, day, minutes, etc.
timer.Tick += timer_Tick;//whenever time elapsed, this function will be called
timer.Start();//start timer here
}
void timer_Tick(object sender, object e)//timer function
{
elapsed_time++;//just to save record of second elapsed
status.Text = "Time Elapsed: " + elapsed_time.ToString() + " sec"; //display user elapsed time
}
private void stop_Click(object sender, RoutedEventArgs e)//when stop button is clicked
{
elapsed_time = 0;//reset timer
timer.Stop();//stop current timer
status.Text = "Press Start Timer to Restart Timer!";//reset text
}
}
Step # 4: Build and run. That's all. Congratulation, You added timer to your app project.