I am having problem using webbrowser control to correctly display html. My goal is to add custom html to a webbrowser control, have it displayed, and save the screenshot of that as png. Currently I am using Document.OpenNew and Document.Write(htmlText) and Application.DoEvents(). However since I am running this in a background thread, sometimes it deadlocks. I know the culprit is Application.DoEvents() which is giving me troubles.
However, if I remove that and set the html directly to DocumentText property, how do I know when it is fully “rendered” or loaded. I used the DocumentCompleted Event but that does not seem to work since the image that is saved is still empty even after the event fires.
I also have the thread as STA.
Here is the existing code:
Thread th = new Thread(new ThreadStart(createImage));
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join(TIMEOUT);
private void createImage() {
var browser = new WebBrowser();
var doc = browser.Document;
doc.OpenNew(false);
doc.Write("<html><body>....</body><html>)");
//loop for few seconds
for(int i=0; i<20; i++)
{
Application.DoEvents();
Thread.Sleep(100);
}
//save to file as png.
}
Here is the code I am trying:
private void createImage() {
var browser = new WebBrowser();
bool docComplete = false;
browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(
(Object sender, WebBrowserDocumentCompletedEventArgs args) =>
{ docComplete = true; }
);
browser.DocumentText = "<html>.....";
while (!_docComplete)
{
Thread.Sleep(100);
}
// save image
// :-( not working
}
You have to create thread as STA, that is only the way to run WebBrowser in a background thread.
There is no information about waiting in HtmlDocument.Write Method. If is yet required then you can add DocumentCompleted handler instead of DoEvents