Getting WebBrowser Control To Work In Console Application?
Asked Answered
T

2

12

I have a printer class that is capable of printing HTML via the WebBrowser object. I want to be able to print from a console application, but I get an error when my printer class tries to create a WebBrowser object:

WebBrowser browser = new WebBrowser();

Error:

ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot 
be instantiated because the current thread is not in a 
single-threaded apartment.  

I tried adding a reference to System.Windows.Forms into my console application but that didn't work. I don't have the slightest idea of what's going on here, but I would appreciate the help.

Together answered 1/4, 2011 at 21:55 Comment(1)
If still interested, have a loop at this implementation.Turnover
M
22

Add STAThread attribute to your main method.

[STAThread]
public static Main()
{
    ...
}

Update: Here what you should do with thread where Browser is created

thread.SetApartmentState(ApartmentState.STA);

Update 2:

If one thread per app:

Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
Maurinemaurise answered 1/4, 2011 at 21:57 Comment(3)
My program runs with [STAThread], but it doesn't actually print.Together
I have a brand new console application that calls the print method from my print class in the Main method. I don't think I'm creating any other threads in my console application. Please let me know if that doesn't answer your question thanks.Together
I don't understand how you would set "therad" to the current thread? My WebBrowser opens just from the main printer class. I really appreciate the help so far :)Together
B
10

A console mode app and WebBrowser are water and fire. You need to follow the single-threaded apartment contract for a thread to use WebBrowser:

  • must be an STA, use [STAThread] on Main() or Thread.SetApartmentState() if you create a thread.
  • must pump a message loop, Application.Run() available in Winforms or WPF.

The second requirement is a hard one for WebBrowser, it won't fire its events if you don't use it. Check this answer for the code to create a thread that runs WB. A GUI app based on Winforms or WPF will always have its main thread already suitable to use WB.

Barrera answered 1/4, 2011 at 22:53 Comment(1)
Thank you for the Thread.SetApartmentState() tip, in SSIS I can't use [STAThread] and I spent a lot of time looking for an alternative!Goran

© 2022 - 2024 — McMap. All rights reserved.