Timer in WPF


  In this demo, Demonstrate you how to use timer in WPF(Window Presentation Foundation). For using the timer first we need to use this namespace “using System.Windows.Threading;” .Create one “DispatcherTimer()” object called “Timer”.

Download:   “http://www.4shared.com/file/-1Z0xy1_/timer.html ”

       

Write the following code :

Code :

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;
using System.Windows.Threading;

namespace timer

{

    /// <summary>

    /// Interaction logic for MainWindow.xaml

    /// </summary>

    ///

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

            Timer = new DispatcherTimer();

        }

        private DispatcherTimer Timer;

       // public event Action DoSomething;

        private int _timesCalled = 0;

        public void timer_Start(int PeriodInSeconds)

        {

            Timer.Interval = TimeSpan.FromSeconds(PeriodInSeconds);

            Timer.Tick += timer_Task;

            _timesCalled = 0;

            Timer.Start();

        }

        public void timer_Stop()

        {

            Timer.Stop();

        }

        int i;

        private void timer_Task(object sender, EventArgs e)

        {

            listBox1.Items.Add(Convert.ToString(DateTime.Now));

        }

        private void button1_Click(object sender, RoutedEventArgs e)

        {

            if (textBox1.Text.Length > 0)

            {

                listBox1.Items.Clear();

                timer_Start(Convert.ToInt32(textBox1.Text));

            }

            else

                MessageBox.Show("set time");

        }

        private void button2_Click(object sender, RoutedEventArgs e)

        {

            Timer.Stop();

        }

    }

}

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s