I'm using the .NET WebBrowser in order to render an html page and save that as a bitmap (got the code from another stackoverflow post). The problem is that the thread that actually starts the web browser never closes.
The thread should close when the StartBrowser Method finishes but it never does because Application.Run never ends.
My question is : how do I close the application after the WebBrowser finishes rendering the page and saves the bitmap ? Adding Application.Exit();
inside the DocumentCompleted event doesn't seem to work.
Code:
public class DotNetRenderer : IHtmlRenderer
{
static Bitmap bmp;
Thread th;
public void initializeRenderer()
{
}
public Bitmap renderHtml(string htmlContent)
{
th = new Thread(() => StartBrowser(htmlContent));
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join();
return bmp;
}
public static void StartBrowser(string source)
{
var webBrowser = new WebBrowser();
webBrowser.ScrollBarsEnabled = false;
webBrowser.DocumentCompleted +=
webBrowser_DocumentCompleted;
webBrowser.DocumentText = source;
Application.Run();
}
static void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var webBrowser = (WebBrowser)sender;
bmp = new Bitmap(webBrowser.Width, webBrowser.Height);
webBrowser.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height));
Application.ExitThread();
}
}
Application.ExitThread() does what I want, but now I don't know why the webBrowser Width and Height are always (250,250) regardless of the input HTML.