简体   繁体   中英

Get a screenshot of the web browser control?

There are a lot threads about this but none of them were clear and none I tried actually even worked right.

What is the code to get the contents of the entire web browser control (even that which is off screen)?

It looks like they did have:

webBrowser1.DrawToBitmap(); // but its unsupported and doesnt work
  1. 3rd party api - not wasting my time
  2. .DrawToBitmap and nonanswer-links
  3. 100 wrong answers
  4. just takes a screenshot

Try to make sure you are calling the method in the DocumentCompleted event.

webBrowser1.Width = wb.Document.Body.ScrollRectangle.Width;
webBrowser1.Height = wb.Document.Body.ScrollRectangle.Height;

Bitmap bitmap = new Bitmap(webBrowser1.Width, webBrowser1.Height);
webBrowser1.DrawToBitmap(bitmap, new Rectangle(0, 0, webBrowser1.Width, webBrowser1.Height));

I was working on a similiar function in my project last week, read a few posts on this topic including your links. I'd like to share my experience:

The key part of this function is System.Windows.Forms.WebBrowser.DrawToBitmap method.

but its unsupported and doesnt work

It is supported and does work, but not always works fine. In some circumstances you will get a blank image screenshot(in my experience, the more complex html it loads, the more possible it fails. In my project only very simple and well-formatted htmls will be loaded into the WebBrowser control so I never get blank images).

Anyway I have no 100% perfect solution either. Here is part of my core code and hope it helps (it works on ASP.NET MVC 3).

using (var browser = new System.Windows.Forms.WebBrowser())
{
     browser.DocumentCompleted += delegate
     {
         using (var pic = new Bitmap(browser.Width, browser.Height))
         {
             browser.DrawToBitmap(pic, new Rectangle(0, 0, pic.Width, pic.Height));
             pic.Save(imagePath);
         }
     };

     browser.Navigate(Server.MapPath("~") + htmlPath); //a file or a url
     browser.ScrollBarsEnabled = false;

     while (browser.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
     {
         System.Windows.Forms.Application.DoEvents();
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM