1

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.

Community
  • 1
  • 1
Adrian Buzea
  • 826
  • 2
  • 11
  • 33
  • Well, it seems that Application.ExitThread() works. But now the problem is that the web browser doesnt get the correct html width and height (makes it 250x250) cropping away a big chunk of the original html. – Adrian Buzea Jun 04 '15 at 07:29
  • If you have more to add to your question, please [edit] it. You should never need to comment, directly, on your own question. – Damien_The_Unbeliever Jun 04 '15 at 07:36

0 Answers0