×
Namespaces

Variants
Actions

Stop Watch using Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search

This article explains how to create stop watch in Windows Phone. It extends the article: Implement Timer control in Windows Phone.

WP Metro Icon UI.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata
Code Example
Source file: Media:StopWatch.zip
Tested with
Devices(s): Windows Phone Emulator
Compatibility
Platform(s): Windows Phone 7.5, 8
Windows Phone 8
Windows Phone 7.5
Article
Keywords: DispatcherTimer , Stop watch
Created: girishpadia (13 Oct 2011)
Last edited: hamishwillee (02 Jul 2013)

Introduction

This code example creates a simple stop watch which you can start and stop using the buttons Start Clock and Stop respectively. The example uses DispatcherTimer to update the stopwatch every second and lists how long the timer ran (calculated from current DateTime when the buttons are pressed).

StopWatch.jpg

Implementation

  1. Create a new "Silverlight" project using C# and name the project as "StopWatch".
  2. Drag one textblock from the toolbox and name it txtClock
  3. Drag two buttons and place them just below the txtClock as shown in the application image below. Name the buttons btnStart and btnStop respectively.
  4. In the XAML file, add the event handlers for the newly created buttons by adding the attribute
    Click="btnStart_Click"
    in the btnStart tag and
    Click="btnStop_Click"
    in the btnStop tag. Alternatively, just double click both buttons in the layout view.
  5. Drag another textblock and name it lblTimer and place it below the buttons.
  6. Copy and paste following code into your application.
using System;
using Microsoft.Phone.Controls;
using System.Windows.Threading;
namespace StopWatch
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
DateTime lastTime,startTime;
public MainPage()
{
InitializeComponent();
}
void OnTimerTick(Object sender, EventArgs args)
{
txtClock.Text = DateTime.Now.ToString();
}
private void btnStart_Click(object sender, System.Windows.RoutedEventArgs e)
{
DispatcherTimer newTimer = new DispatcherTimer();
newTimer.Interval = TimeSpan.FromSeconds(1);
newTimer.Tick += OnTimerTick;
newTimer.Start();
lastTime = DateTime.Now;
startTime = DateTime.Now;
lblTimer.Text = "Start time : " + lastTime.ToString() + "\n";
}
private void btnStop_Click(object sender, System.Windows.RoutedEventArgs e)
{
DateTime endTime = DateTime.Now;
TimeSpan span = endTime.Subtract(startTime);
lblTimer.Text += "Seconds from begining: "+span.TotalSeconds.ToString()+"\n";
span = endTime.Subtract(lastTime);
lblTimer.Text += "Seconds from last stop: " + span.TotalSeconds.ToString() + "\n\n";
lastTime = DateTime.Now;
 
}
}
}

Tested On

The application is tested on Windows Phone Emulator.

This page was last modified on 2 July 2013, at 14:11.
213 page views in the last 30 days.
×