Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass in an owner window to MessageBox.Show on a different thread?

Tags:

.net

I am trying to figure out Messagebox( ownerWindow, ... ).

Using reflector I see that the ownerWindow defaults to the ActiveWindow for the thread.

So the only time I need the ownerWindow parameter is to call Show from another thread.

However when I try this, I get a cross threading exception.

    private void button1_Click( object sender, EventArgs e ) {
        new Thread( () => MessageBox.Show( this, "Test" ) ).Start();
    }

So it looks like the only time I need the explicitly state the owner window, I cann't use it!

like image 210
jyoung Avatar asked Dec 04 '25 20:12

jyoung


2 Answers

You will have to do a BeginInvoke to marshal the call to the UI thread.

The code below is a simple example how you can do it. I haven't compiled it, so there might be errors in it, but it might give you some pointers.

private delegate void ThreadExecuteDelegate(object args);

public void StartThread
{
   Thread thread = new Thread(new ParameterizedThreadStart(ThreadExecute));
   thread.Start((IWin32Window)this);
}

private void ThreadExecute(object args)
{
    if(this.InvokeRequired)
    {
        this.BeginInvoke(new ThreadExecuteDelegate(ThreadExecute), args);
        return;
    }   

    IWin32Window window = (IWin32Window)args;
    MessageBox.Show(window, "Hello world");
}
like image 172
Patrik Svensson Avatar answered Dec 06 '25 09:12

Patrik Svensson


It was the Control.Handle getter that was testing for cross threading.

Adding the following code fixes things.

   public class Win32Window :IWin32Window {
        IntPtr handle;
        public Win32Window( IWin32Window window ) {
            this.handle = window.Handle;
        }

        IntPtr IWin32Window.Handle {
            get { return handle; }
        }
    }

    private void button1_Click( object sender, EventArgs e ) {
        IWin32Window window = new Win32Window( this );
        new Thread( () => MessageBox.Show( window, "Test" ) ).Start();
    }
like image 31
jyoung Avatar answered Dec 06 '25 11:12

jyoung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!