0

Iam a noobi i have this problem , i need to make a timer for my program ,which starts when the user clicks a specific button. and then to output the countdown in to a label

Thanks in advance

nashat
  • 11
  • 2

2 Answers2

1

This was pulled from production so I'm sure it works:

...
     _Timer = new DispatcherTimer();
     _Timer.Interval = TimeSpan.FromMilliseconds(125);
     _Timer.Tick += new EventHandler(_Timer_Tick);
     _Timer.IsEnabled = true;
     _Timer.Start();
...

    void _Timer_Tick(object sender, EventArgs e)
    {
         try {
           ...Do your thing here
         } catch (Exception x){
             Debug.WriteLine("Error: "+x);
         }
    }
Sten Petrov
  • 10,943
  • 1
  • 41
  • 61
1

The DispatcherTimer is located in the System.Windows.Threading Namespace.

Something like this should work:

public partial class MainWindow : Window
{
    int count = 0;
    System.Windows.Threading.DispatcherTimer tmr = new System.Windows.Threading.DispatcherTimer();
    public MainWindow()
    {
        InitializeComponent();
        tmr.Interval = new TimeSpan(0, 0, 2);
        tmr.Tick += new EventHandler(tmr_Tick);
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        tmr.Start();
    }

    void tmr_Tick(object sender, EventArgs e)
    {
        label1.Content = count += 1;
    }

    private void button2_Click(object sender, RoutedEventArgs e)
    {
        tmr.Stop();
    }
}
Mark Hall
  • 53,938
  • 9
  • 94
  • 111