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 Web开发者_如何学PythonBrowserDocumentCompletedEventHandler(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
You can set AspCompat="true" in the page's page directive and it will run in an STA. After you have done that your first example should work
WinInet is not supported for use in services, which means any application that uses WinInet, such as IE's webbrowser control, isn't supported in services (e.g. asp.net services).
Why are you using the webbrowser control in an asp.net based application?
It looks like you want to have a browser inside a browser.
Using it, you are limiting the audience to use IE (and Windows, I suppose).
Can't you use IFrame or Ajax or some other alternative?
Post your reasons & people might suggest a better alternative.
I was also trying to use WebBrowser control in my .Net page. Found this article which exactly answers your question.
Capture Screenshot (Snapshot) Image of Website (Web Page) in ASP.Net using C# and VB.Net
精彩评论