2

I was moving over a method to my winforms project from a wpf project.

I have no idea how to convert over Dispatcher to winforms.

Can anyone help me out?

void gm_MoveDownByThread()
{
    this.Dispatcher.Invoke((Action)(() =>
    {
        KeyDownMethod(Key.Down);
    }));
}
Franta
  • 57
  • 1
  • 7
  • 3
    Take a look at [Control.Invoke](https://msdn.microsoft.com/en-us/library/zyzhdc6b(v=vs.110).aspx). – Clemens Feb 21 '17 at 19:48
  • See also e.g. https://stackoverflow.com/questions/13292628/dispatching-events-into-right-thread, https://stackoverflow.com/questions/18134822/how-do-i-convert-wpf-dispatcher-to-winforms, etc. – Peter Duniho Feb 21 '17 at 20:03

1 Answers1

1

If you're running from the UI thread, then the following method would be the most generic one, and will work both in WPF and in WinForms:

SynchronizationContext.Current.Send(_ =>
            {
                //anything you wish.
            }, null);

Both the WinForms dispatcher and the WPF dispatcher are implementation of the SynchronizationContext that enqueue the requested action into the UI thread queue. This way you don't use anything specific.

If you're running your code outside the UI thread, then the SynchronizationContext.Current will reference to the "default" implementation which isn't what you're looking for (it doesn't run the actions inside the UI thread, but just in the ThreadPool). So, in that case if you have a reference to any UI control you can use the BeginInvoke method of anything that inherits from the Control class.

Hope this helps.

Shahar Gvirtz
  • 2,418
  • 1
  • 14
  • 17