I tried to use the WebBrowser control in an ASP .NET application:
public BrowserForm()
{
webBrowser1 = new WebBrowser();
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
private void webBrowser1_DocumentCompleted(Object sender, WebBrowserDocumentCompletedEventArgs e)
{
// code here
}
But got error:
'8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment
Then I did something like this:
public BrowserForm()
{
ThreadStart ts = new ThreadStart(StartThread);
var t = new Thread(ts);
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
[STAThread]
public void StartThread()
{
webBrowser1 = new WebBrowser();
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
[STAThread]
private void webBrowser1_DocumentCompleted(Object sender, WebBrowserDocumentCompletedEventArgs e)
{
//code here
}
But still it's not working for me as desired...giving me weired errors like:
Error HRESULT E_FAIL has been returned from a call to a COM component
Any work around?? I'm not an expert of threading or COM but trying to convert a WindowApplication to WebApplication which takes a screenshot of a web page provided a URL. :(
Check this codeproject article Using the WebBrowser Control in ASP.NET.
In that article go to the Technical Specifications section, and there you can see how he handled this STA thread issue.
First of all, a WebBrowser control has to be in a thread set to single thread apartment (STA) mode (see MSDN), so I need to create a thread and call the SetApartmentState() method to set it to ApartmentState.STA before starting it.
Hope this helps
Cheer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With