c# - Web 应用程序中的 WebBrowser 控件

标签 c# .net asp.net webbrowser-control

我尝试在 ASP .NET 应用程序中使用 WebBrowser 控件:

public BrowserForm()
        {
            webBrowser1 = new WebBrowser();
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        }
private void webBrowser1_DocumentCompleted(Object sender, WebBrowserDocumentCompletedEventArgs e)
    {
   // code here
    }

但出现错误:

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

然后我做了这样的事情:

     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
        }

但它仍然无法按预期工作...给我一些奇怪的错误,例如:

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

有什么解决方法吗??我不是线程或 COM 方面的专家,但我试图将 WindowApplication 转换为 WebApplication,它获取提供 URL 的网页的屏幕截图。 :(

最佳答案

查看此代码项目文章 Using the WebBrowser Control in ASP.NET .

在那篇文章中,转到“技术规范”部分,在那里您可以看到他是如何处理这个 STA 线程问题的。

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.

希望对你有帮助

欢呼

关于c# - Web 应用程序中的 WebBrowser 控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2324316/

相关文章:

c# - 使用 Silverlight 读写 EXIF 数据

c# - 如何对列表进行排序,将 map 从旧位置保存到新位置?

c# - 使用 Rally REST API,如何查询并返回一个*完整*的 JSON 对象?

c# - 如何将 xml 序列化对象从 ASP.NET 发送到 Silverlight

javascript - RegisterClientScriptBlock 不起作用

c# - 确定最接近类的子接口(interface)

c# - 如何更改 TextCompositionEventArgs 中的文本

c# - 如何处理这种竞争条件?

.net - 在绑定(bind)到 DataGridView 的 DataTable 上触发更新

asp.net - 在 ASP.NET 中内联获取当前 URL