Crystal
Crystal

Reputation: 29518

Creating another thread to get the current window (System.Windows.Application.Current.MainWindow)

I need the current window to show a custom MessageBox. I do this:

Window owner = System.Windows.Application.Current.MainWindow;

sometimes it works. Where it doesn't work, I get this error:

System.InvalidOperationException: {"The calling thread cannot access this object because a different thread owns it."}
InnerException: null
Message: The calling thread cannot access this object because a different thread owns it.

Would a solution to be to kick this call off to a separate thread than the main thread? If so, how do I do that? Thanks.

Upvotes: 3

Views: 6937

Answers (2)

karollo
karollo

Reputation: 595

Working alternative of Reed Copsey's answer:

System.Windows.Application.Current.Dispatcher.Invoke((Action)delegate
{
       Window owner = System.Windows.Application.Current.MainWindow;

       // Use owner here - it must be used on the UI thread as well..
       ShowMyWindow(owner);
});

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564751

You'll need to use the Dispatcher and Invoke/BeginInvoke to marshal the call back to the UI thread:

System.Windows.Application.Current.Dispatcher.Invoke((Action)() =>
{
       Window owner = System.Windows.Application.Current.MainWindow;

       // Use owner here - it must be used on the UI thread as well..
       ShowMyWindow(owner);
});

Upvotes: 12

Related Questions