Using DispatcherTimer To Create A Timer In WPF

09-03-2012
//
http://pagead2.googlesyndication.com/pagead/show_ads.js

WPF doesn’t have a straightforward Timer control that you can drag and drop from the Toolbox.

However, ther’s still a straightforward easy way to implement this.

You can use the provided System.Windows.Threading.DispatcherTimer class for this

It’s easy as abc.

Steps:

1 Create an instance

System.Windows.Threading.DispatcherTimer TimerName = new System.Windows.Threading.DispatcherTimer() ;

2 Create an event handler for DispatcherTimer.Tick event

This is similar to what you used to write after double clicking on the timer under the Timer_Tick method.

Use following structure (method signature) to create the event handler and put all the code you want the timer to do in it.

private void methodName(object sender, EventArgs e)

{

… put your code for the timer here

}

3 Assign The Tick Event Handler To The Timer

TimerName.Tick += methodName ;

3 Set An Interval

Specify the interval for the timer. Or in other words tell the timer how often you want it to fire.

You have to use a TimeSpan value for this. Simply create a new TimeStamp and set the time.

Briefly: System.TimeSpan constructor takes three parameters (hh – number of hours, mm – number of minutes, ss – number of seconds)

There are  overloaded constructors that accept days and milliseconds if you want.

i.e. TimerName.Interval = new TimeSpan(0, 0, 1) ;  // this timer will fire every one second

4 Start the timer…

TimerName.Start() ;

Sample Code


private void btnStartClock_Click(object sender, RoutedEventArgs e)
{
System.Windows.Threading.DispatcherTimer digitalClock = new System.Windows.Threading.DispatcherTimer();
digitalClock.Interval = new System.TimeSpan(0, 0, 1);
digitalClock.Tick += digitalClock_Tick;
digitalClock.Start();
}

private void digitalClock_Tick(object sender, EventArgs e)
{
this.lblClock.Content = string.Format("{0} : {1} : {2}",DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
}

Output:

The label will display the time in “Hour : Minute : Second” format (i.e. 11 : 25 : 36) and the timer will refresh it every second.

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek
//
http://pagead2.googlesyndication.com/pagead/show_ads.js

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: