How to push a message loop in WinForms?

292 Views Asked by At

In WPF, I can push a message loop using Dispatcher.PushFrame.

What is the equivalent in WinForms? I'm familiar with DoEvents but that must be called in a loop which can spin the CPU instead of the very efficient approach of just waiting for a message or for an event to signal to exit (like Dispatcher.PushFrame has).

2

There are 2 best solutions below

1
On

This is the equivalent:

        System.Threading.SendOrPostCallback callback = o =>
        {
            this.Text = "Hello" + o.ToString(); // "Hello42"
        };
        WindowsFormsSynchronizationContext.Current.Post(callback, 42);

The 42 is a state parameter that gets past to the callback.

You can also do this:

        this.BeginInvoke((Action)(() => this.Text = "Hello"));

BTW, you should never ever ever use DoEvents - it's a great way to introduce bugs in to your code and is really only there for VB6 compatibility.

0
On

I was able to include WindowsBase to my project's references and just use Dispatcher.PushFrame and frame.Continue = false as usual.

Any caveats with wpf-winforms interop apply, and it does require part of wpf to be referenced, but it should still be better than DoEvents (which has severe pitfalls).