我在我的表单中使用Web浏览器导航到多个页面。我想在完全加载后获取最后一页的屏幕截图。我编写了webBrowser1_DocumentCompleted中的屏幕截图。然而,在页面加载之前它会截取屏幕截图。我很困惑我可以截取屏幕截图。我在谷歌发现了LoadCompleted事件但不确定如何使用。请帮帮我。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
using System.Drawing.Imaging;
namespace CC
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
string url = "http://www.lll.com";
webBrowser1.Navigate(new Uri(url));
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
catch (Exception ex)
{
}
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string AbsoluteURL = e.Url.AbsolutePath.ToString();
int count = 0;
switch (AbsoluteURL)
{
case "Page1":
var loginControl = webBrowser1.Document.GetElementById("user");
var passwordControl = webBrowser1.Document.GetElementById("password");
var btn = webBrowser1.Document.GetElementById("Submit");
if (loginControl != null)
loginControl.SetAttribute("value", "XXX");
if (passwordControl != null)
passwordControl.SetAttribute("value", "YYY");
var elems = webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement elem in elems)
{
if (elem.GetAttribute("tabindex") == "3")
{
elem.InvokeMember("click");
}
}
break;
case"Page2": // THIS IS NOT WORKING. TAKING SCREEN SHOT BEFORE PAGE GETTING LOADED FULLY. NEED HELP HERE
using (Bitmap bitmap = new Bitmap(webBrowser1.Width, webBrowser1.Height, PixelFormat.Format24bppRgb))
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.CopyFromScreen(
PointToScreen(webBrowser1.Location),
new Point(0, 0),
webBrowser1.Size);
bitmap.Save(@"C:\123.bmp");
}
break;
default:
Console.WriteLine("Better try again");
break;
}
}
}
}
}
答案 0 :(得分:0)
试试这个。
protected void Capture(object sender, EventArgs e)
{
string url = "www.google.com";
Thread thread = new Thread(delegate()
{
using (WebBrowser browser = new WebBrowser())
{
browser.ScrollBarsEnabled = false;
browser.AllowNavigation = true;
browser.Navigate(url);
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;
//do what do you want
}

答案 1 :(得分:0)
根据我的经验,导航和文档加载与实际呈现文档不同。我会查看ReadyState
https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowserreadystate%28v=vs.110%29.aspx以确定文档是否实际呈现而不仅仅是已加载。