我尝试在 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/