简体   繁体   English

获取Web浏览器控件的屏幕截图?

[英]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)? 获取整个Web浏览器控件内容的代码是什么(即使是屏幕外的内容)?

It looks like they did have: 看起来他们确实有:

webBrowser1.DrawToBitmap(); // but its unsupported and doesnt work
  1. 3rd party api - not wasting my time 第三方api - 不浪费我的时间
  2. .DrawToBitmap and nonanswer-links .DrawToBitmap和nonanswer-links
  3. 100 wrong answers 100个错误答案
  4. just takes a screenshot 只是截图

Try to make sure you are calling the method in the DocumentCompleted event. 尝试确保在DocumentCompleted事件中调用方法。

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. 该函数的关键部分是System.Windows.Forms.WebBrowser.DrawToBitmap方法。

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). 在某些情况下,你会得到一个空白图像截图(根据我的经验,它加载的更复杂的html,它失败的可能性越大。在我的项目中,只有非常简单和格式良好的htmls将加载到WebBrowser控件中,所以我永远不会得到空白图像)。

Anyway I have no 100% perfect solution either. 无论如何,我也没有100%完美的解决方案。 Here is part of my core code and hope it helps (it works on ASP.NET MVC 3). 这是我的核心代码的一部分,希望它有所帮助(它适用于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();
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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