1

I tried to catch the end of a window resizing process using a timer in WPF. First I used a timer from System.Timers, it doens't work an I changed to the solution as stated here (System.Windows.Threading.DispatcherTimer):

How to catch the ending resize window?

Everthing is ok now, but does anybody know the reason of this behavior ? An earlier solution to get the end of a resizing operation used a classic timer from System.Timers namespace. Am I forced to use the DispatcherTimer ?

Thanks in advance ...

Community
  • 1
  • 1
Mica
  • 35
  • 4
  • What do you mean by "it doesn't work"? It should work with a regular `System.Timers.Timer` if you explicitly invoke your UI code on the UI thread. `DispatcherTimer`, among other things, just does that for you implicitly. – Patrice Gahide Jan 24 '15 at 11:01
  • The elapsed handler from Systems.Timers.Timer is called from another thread, not the UI thread, that's the reason, invoking the UI thread from here does the job, thanks ! – Mica Jan 24 '15 at 11:44

1 Answers1

1

You can do the same thing with System.Timers.Timer. Note that it has different (but similar) methods and properties than the DispatcherTimer.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.SizeChanged += MainWindow_SizeChanged;
        _resizeTimer.Elapsed += _resizeTimer_Elapsed;
    }

    private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        _resizeTimer.Stop();
        _resizeTimer.Start();
    }

    System.Timers.Timer _resizeTimer = new System.Timers.Timer { Interval = 1500 };

    void _resizeTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        _resizeTimer.Stop();

        System.Diagnostics.Debug.WriteLine("SizeChanged end");
        //Do end of resize processing

        //you need to use BeginInvoke to access the UI elements
        //this.Dispatcher.BeginInvoke(...)
    }
}

One thing is more important, that System.Timers.Timer runs on a different thread other than the UI thread, which means you can't directly manipulate UI elements from within the _resizeTimer_Elapsed method. You need to use BeginInvoke to marshal the call back to the UI thread.

Find the differences between System.Timers.Timer and DispatcherTimer. There are many questions and answers on this subject. I just want to show you how to do it with the classic timer.

kennyzx
  • 12,845
  • 6
  • 39
  • 83