最近用到WebBrowser控件,遇到很多问题,也学习了不少新的东西。下面是我在C#下写的关于WebBrowser控件使用的代码。
1、WebBrowser常用属性
.Refresh();//刷新
.GoBack();//后退
.GoForward();//前进
.Navigate(new Uri(address)); //打开链接
.Dock = DockStyle.Fill; //完全停靠在父容器中
.ScriptErrorsSuppressed = true ; //关闭错误显示
Uri a = new Uri(WebBrowser.Document.ActiveElement.GetAttribute("href"));//获取点击中的链接地址
2、WebBrowser常用事件处理
.Navigated += new WebBrowserNavigatedEventHandler(WebBrowser_Navigated);//加载中处理事件
.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser _DocumentCompleted);//页面加载完成处理事件
.NewWindow += new CancelEventHandler(WebBrowser _NewWindow);//新的窗口中打开页面
3、事件处理函数
3.1、打开新连接
// Navigates to the given URL if it is valid.
private void Navigate(WebBrowser web,String address)
{
if (String.IsNullOrEmpty(address)) return;
if (address.Equals("about:blank")) return;
if (!address.StartsWith("http://")) address = "http://" + address;
try
{
WebBrowser.Navigate(new Uri(address));
}
catch (System.UriFormatException)
{
return;
}
// Updates the URL in TextBoxAddress upon navigation.
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
toolStripTextBox1.Text = WebBrowser.Url.ToString();
}
}
3.2、新窗口处理
private void WebBrowser_NewWindow(object sender, CancelEventArgs e)
{
WebBrowser webb = new WebBrowser();
WebBrowser = WebBrowsers[webtab.SelectedIndex];
webb.Name = "webb" + webtab.TabCount;
Uri a = new Uri(WebBrowser.Document.ActiveElement.GetAttribute("href"));
webb.Url = a;
webb.Dock = DockStyle.Fill;
TabPage p = new TabPage();
p.Controls.Add(webb);
webtab.TabPages.Add(p);
webtab.SelectedTab = p;
webb.NewWindow += new CancelEventHandler(WebBrowser_NewWindow);
e.Cancel = true;//取消在默认浏览器中打开
}
3.3、用户自动登陆处理
#region 用户自动登陆
private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
HtmlDocument log_auto = WebBrowser.Document;
HtmlElement log_btn = null;
foreach (HtmlElement em in log_auto.All) //轮循
{
string str = em.Name;
string id = em.Id;
if ((str == "username") || (str == "password") || (str == "submit")) //减少处理
{
switch (str)
{
case "username": em.SetAttribute("value", usernamexml);
break; //赋用户名
case "password": em.SetAttribute("value", userpasswordxml );
break; //赋密码
case "submit": log_btn = em;
break; //获取submit按钮
default:
break;
}
}
}
log_btn.InvokeMember("click"); //触发submit事件
}
#endregion