Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebBrowser Control in a web application

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. :(

like image 561
Manish Avatar asked Feb 24 '10 07:02

Manish


1 Answers

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

like image 168
RameshVel Avatar answered Oct 19 '22 08:10

RameshVel