title: .net web page capture with WebBrowser.DrawToBitmap contains all white or partially loaded page
body: <p>I used the seemingly ridiculously easy code found <a href="http://www.aspsnippets.com/Articles/Capture-Screenshot-Snapshot-Image-of-Website-Web-Page-in-ASPNet-using-C-and-VBNet.aspx" rel="nofollow">here</a></p>
  
  <pre><code>protected void Capture(object sender, EventArgs e)
  
  {
  
  string url = txtUrl.Text.Trim();
  
  Thread thread = new Thread(delegate()
  
  {
  
      using (WebBrowser browser = new WebBrowser())
  
      {
  
          browser.ScrollBarsEnabled = false;
  
          browser.AllowNavigation = true;
  
          browser.Navigate(url);
  
          browser.Width = 1024;
  
          browser.Height = 768;
  
          browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(DocumentCompleted);
  
          while (browser.ReadyState != WebBrowserReadyState.Complete)
  
          {
  
              System.Windows.Forms.Application.DoEvents();
  
          }
  
      }
  
  });
  
  thread.SetApartmentState(ApartmentState.STA);
  
  thread.Start();
  
  thread.Join();
  }
  
  
  
  private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
  
  {
  
  WebBrowser browser = sender as WebBrowser;
  
  using (Bitmap bitmap = new Bitmap(browser.Width, browser.Height))
  
  {
  
      browser.DrawToBitmap(bitmap, new Rectangle(0, 0, browser.Width, browser.Height));
  
      using (MemoryStream stream = new MemoryStream())
  
      {
  
          bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
  
          byte[] bytes = stream.ToArray();
  
          imgScreenShot.Visible = true;
  
          imgScreenShot.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes);
  
      }
  
  }
  
  }
  </code></pre>
  
  <p>However, when I run it against a facebook url, or certain other sites, I get an all white result image.  Sometimes I get <em>some</em> of the initial page, so it seems like a matter of timing what with all the new web technologies.</p>
  
  <p>WebBrowser may be indicating a ReadyState of Complete, even though elements on the page are continuing to load.</p>
  
  <p>If I add some Thread.Sleeps, it doesn't appear to help.</p>