Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF with Windows Forms - STAThread

Tags:

c#

winforms

wpf

sta

I am a newbie to WPF and have a couple of questions about WPF and Windows Forms integration.

I have an existing Visual C# Windows Forms application. I would like to integrate it with a WPF window, that can be shown on a button click. This was not possible as WPF expects the calling thread to be a STAThread and by default WinForm assumes that the thread is an MTAThread. I tried spawning a new thread with an apartment state of STAThread for calling the WPF UI but that did not work. I tried using the Dispatcher.BeginInvoke method and Background Worker as well, but none of them resolved the issue.

1) Can we make a call to WPF window/control without marking the Main as an STAThread? If it is possible, Can anyone please point me to a proper direction? 2) If the only way to accomplish this is by making the Main Thread an STAThread, will there be any impact to the general performance/responsiveness of the application.

Thanks in advance.

like image 275
user26242 Avatar asked Oct 19 '08 16:10

user26242


1 Answers

I think the simplest solution is to make your WinForms thread execute in an STA. There is nothing wrong with having an STA thread winforms app (it is in fact often the default).

You can fix this by adding the following line to the main method of your program:

[STAThreadAttribute]
static void Main(string[] args)
like image 173
JaredPar Avatar answered Oct 02 '22 12:10

JaredPar