WPF Get UI Thread, or how to show a window from NON-UI Thread
Asked Answered
B

2

6

I realized a WPF Control Library to use as an Addin in MS Office 2007.

The WPF-Class is instantiated by the host and creates a toolbar with some buttons in MS Office. By clicking a button the WPF window should appear. The problem is that I always receive the following error: "The calling thread must be STA, because many UI components require this." My main function is marked as [STAThread].

It seems that the button_Click event runs in an other thread than the UI thread.

I tried to use a dispatcher, but that didn't work.

Dispatcher.CurrentDispatcher.Invoke(
               System.Windows.Threading.DispatcherPriority.Normal,
               new Action(
                 delegate()
                 {
    wpfform wf = new wpfform();
    wf.ShowDialog();
     ));

I think the module gets a wrong dispatcher, but I don't know exactly. Next I tried to start the window in an separate STA thread and join the thread, but this didn't work either. As I removed the [STAThread] Attribute from the main function the window started, but i was unable to access office (because i'm in a separate thread).

Thread workerThread = new Thread(_ShowDialog);
workerThread.SetApartmentState(ApartmentState.STA);
workerThread.Start();
workerThread.Join();

Is it possible to determine the UI thread and create a dispatcher for this thread, or how can I come back to the UI thread?

Beauvais answered 26/5, 2010 at 15:1 Comment(0)
D
9

You will need to use the application UI dispatcher. Try using:

Application.Current.Dispatcher.Invoke(...)
Deontology answered 26/5, 2010 at 15:5 Comment(2)
I believe the default name for Application is App in WPF applications.Deontology
Unfortunately Application.Current is null :( Any other ideas?Beauvais
O
2

You can use SynchronizationContext, which is described here in stackoverflow: Using SynchronizationContext for sending events back to the UI for WinForms or WPF (you have to "capture" context on UI thread, sadly, result of that question is: you should use Application.Current.Dispatcher -- maybe you should look why is null)

Oared answered 9/5, 2015 at 4:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.