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!
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");
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With