Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a timer in WPF?

Tags:

c#

wpf

I am a newbie in timer in wpf and I need a code that every 5mins there is a message box will pop up. .can anyone help me for the simple code of timer.

That's what I tried so far:

System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();  private void test()  {      dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);      dispatcherTimer.Interval = new TimeSpan(0, 0, 1);      dispatcherTimer.Start();  }  private void dispatcherTimer_Tick(object sender, EventArgs e) {      // code goes here  }   private void button1_Click(object sender, RoutedEventArgs e) {      test();  }  
like image 470
user27 Avatar asked Jul 19 '12 11:07

user27


People also ask

How do I make a countdown timer in C#?

Count Down Timer With the Timer Class in C# The Timer class) is used to execute a function inside a separate thread in C#. We can use the Timer function to create a count-down timer in C#. The Timer. Interval property sets the interval between each tick of the timer in milliseconds.

How do I create a timer in Visual Studio?

Select the Toolbox tab, in the Components category, double-click or drag the Timer component to your form. The timer icon, called timer1, appears in a space below the form. Select the Timer1 icon to select the timer. In the Properties window, select the Properties button to view properties.

What is the meaning of WPF?

WPF, stands for Windows Presentation Foundation is a development framework and a sub-system of . NET Framework. WPF is used to build Windows client applications that run on Windows operating system. WPF uses XAML as its frontend language and C# as its backend languages.


2 Answers

In WPF, you use a DispatcherTimer.

System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer(); dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick); dispatcherTimer.Interval = new TimeSpan(0,5,0); dispatcherTimer.Start();   private void dispatcherTimer_Tick(object sender, EventArgs e) {   // code goes here } 
like image 168
Rhys Towey Avatar answered Sep 21 '22 03:09

Rhys Towey


Adding to the above. You use the Dispatch timer if you want the tick events marshalled back to the UI thread. Otherwise I would use System.Timers.Timer.

like image 29
JasonDWilson Avatar answered Sep 20 '22 03:09

JasonDWilson