在Web应用程序WebBrowser控件控件、应用程序、Web、WebBrowser

2023-09-03 04:50:23 作者:陌年微凉

我试图用在ASP .NET应用程序WebBrowser控件:

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   不能被实例化,因为   当前线程不是一个   单线程单元

'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
        }

但仍然是不理想的工作对我来说...给我像weired错误:

But still it's not working for me as desired...giving me weired errors like:

错误HRESULT E_FAIL已返回   通过调用COM组件

Error HRESULT E_FAIL has been returned from a call to a COM component

任何变通?我不是线程或COM而是试图将一个具有WindowApplication来的WebApplication这需要提供一个URL的网页截图的专家。 :(

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

推荐答案

勾选此$ C $的CProject文章的使用在ASP.NET WebBrowser控件。

Check this codeproject article Using the WebBrowser Control in ASP.NET.

在那篇文章转到技术规格部分,在那里你可以看到他是如何处理这个STA线程问题。

In that article go to the Technical Specifications section, and there you can see how he handled this STA thread issue.

首先,WebBrowser控件有   要在一个线程设置为单线程   单元(STA)模式(见 MSDN ),所以我   需要创建一个线程并调用   SetApartmentState()方法来设置它   以ApartmentState.STA开始前,   吧。

VB使用webbrowser控件访问网页

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.

希望这有助于

陈绮贞