Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening a WPF Window in another Thread from a Windows Forms App

OK, I should start this off by saying I'm not sure this is necessarily the right way to deal with this but...

Basically I have created a Window in WPF for displaying notifications in my application (a bit like Outlook New Mail notification). I would like to try and show this Window in it's own thread (it might do some work in the future).

I've created the Window using WPF because it's a bit nicer at handling things like AlwaysOnTop and Fading In and Out.

The application that shows the notification is a 3.5 Windows Forms App. I've seen examples similar to this SOF: C# winforms startup (Splash) form not hiding for showing a Form in a different thread however I'm unable to start a new Message Loop with the WPF Window.

I've tried just calling Notification.Show() in a new thread however the Window never displays.

  1. Is it possible to show this WPF in it's own thread?

  2. Why do I see some resources say that you should not show any UI in a separate thread?

like image 963
MrEdmundo Avatar asked Apr 08 '09 11:04

MrEdmundo


2 Answers

The WPF Threading Model has details on this. Look for "Multiple Windows, Multiple Threads."

Basically, you start a new thread, which creates the relevant window and then calls

System.Windows.Threading.Dispatcher.Run();

in order to run a dispatcher for that window, on the new thread.

like image 101
Jon Skeet Avatar answered Nov 15 '22 22:11

Jon Skeet


  1. Is it possible to show this WPF in it's own thread?

Absolutely. Just create a new STA thread and create and display your Window from it. I've used this technique for a splash screen because the main (UI) thread got really tied up doing other things. It was completely out of my control how much work was being done on the UI thread because of a 3rd party framework we were using.

  1. Why do I see some resources say that you should not show any UI in a separate thread?

Possibly because of the extra complexity involved. If one of your Windows wants to pass data to another, you need to remember that they're executing on separate threads. Therefore, each should use its Dispatcher to marshal calls to the correct thread.

like image 40
Kent Boogaart Avatar answered Nov 15 '22 22:11

Kent Boogaart