Get a screenshot of the web browser control?

我是研究僧i 提交于 2019-12-23 10:26:44

问题


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

回答1:


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();
     }
}



回答2:


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));


来源:https://stackoverflow.com/questions/14167621/get-a-screenshot-of-the-web-browser-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!