在c#编程中,经常会用到webbrowser控件,这里通过实例学习下webbrowser控件的用法。
一、webbrowser常用属性:
.Refresh(); //刷新
.GoBack(); //后退
.GoForward(); //前进
.Navigate(new Uri(address)); //打开链接
.Dock = DockStyle.Fill; //完全停靠在父容器中
.ScriptErrorsSuppressed = true ; //关闭错误显示
Uri a = new Uri(WebBrowser.Document.ActiveElement.GetAttribute("href")); //获取点击中的链接地址
二、webbrowser常用事件处理:
三、webbrowser事件处理函数
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();
}
}
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、用户自动登录处理:
#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