WPF C# - Timer countdown

touyets picture touyets · Aug 14, 2013 · Viewed 11.5k times · Source

How can I implement the following in my piece of code written in WPF C#?

I have a ElementFlow control in which I have implemented a SelectionChanged event which (by definition) fires up a specific event when the control's item selection has changed.

What I would like it to do is:

  1. Start a timer
  2. If the timer reaches 2 seconds then launch a MessageBox saying ("Hi there") for example
  3. If the selection changes before the timer reaches 2 seconds then the timer should be reset and started over again.

This is to ensure that the lengthy action only launches if the selection has not changed within 2 seconds but I am not familiar with the DispatcherTimer feature of WPF as i am more in the know when it comes to the normal Timer of Windows Forms.

Thanks,

S.

Answer

Sheridan picture Sheridan · Aug 14, 2013

Try this:

private int timerTickCount = 0;
private bool hasSelectionChanged = false;
private DispatcherTimer timer;

In your constructor or relevant method:

timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1); // will 'tick' once every second
timer.Tick += new EventHandler(Timer_Tick);
timer.Start();

And then an event handler:

private void Timer_Tick(object sender, EventArgs e)
{
    DispatcherTimer timer = (DispatcherTimer)sender;
    if (++timerTickCount == 2)
    {
        if (hasSelectionChanged) timer.Stop();
        else MessageBox.Show("Hi there");
    }
}

Finally, to make this work, you just need to set the hasSelectionChanged variable when the selection has changed according to your SelectionChanged event.