我正在尝试通过 WebBrowser 控件以编程方式加载网页,以测试该页面
但是,我在简单地创建和导航 WebBrowser 控件时遇到了麻烦。
WebBrowser wb = new WebBrowser();
wb.AllowNavigation = true;
wb.Navigate("http://www.google.com/");
当 Navigate() 运行后通过 Intellisense 检查 Web 浏览器的状态时,WebBrowser.ReadyState 为"未初始化",WebBrowser.Document = null,并且它总体上看起来完全不受我的调用影响。
根据上下文,我在 Windows 窗体对象之外运行此控件:我不需要加载窗口或实际查看页面。
非常感谢任何建议,谢谢!
答案
您应该处理 WebBrowser.DocumentComplete 事件,一旦引发该事件,您将拥有文档等。
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = sender as WebBrowser;
// wb.Document is not null at this point
}
这是一个完整的示例,我在 Windows 窗体应用程序中快速完成并进行了测试。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
WebBrowser wb = new WebBrowser();
wb.AllowNavigation = true;
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
wb.Navigate("http://www.google.com");
}
private void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = sender as WebBrowser;
// wb.Document is not null at this point
}
}
编辑:这是从控制台应用程序运行窗口的代码的简单版本。
using System;
using System.Windows;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
[STAThread]
static void Main(string[] args)
{
Application.Run(new BrowserWindow());
Console.ReadKey();
}
}
class BrowserWindow : Form
{
public BrowserWindow()
{
ShowInTaskbar = false;
WindowState = FormWindowState.Minimized;
Load += new EventHandler(Window_Load);
}
void Window_Load(object sender, EventArgs e)
{
WebBrowser wb = new WebBrowser();
wb.AllowNavigation = true;
wb.DocumentCompleted += wb_DocumentCompleted;
wb.Navigate("http://www.bing.com");
}
void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
Console.WriteLine("We have Bing");
}
}
}