WebBrowser是C#中非常实用的一个控件,本文以实例形式分析了WebBrowser的用法,供大家参考。具体分析如下:
一、WebBrowser常用属性:
.Refresh();//刷新.GoBack();//后退.GoForward();//前进.Navigate(new Uri(address)); //打开链接.Dock = DockStyle.Fill; //完全停靠在父容器中.ScriptErrorsSuppressed = true ; //关闭错误显示Uri a = new Uri(WebBrowser.Document.ActiveElement.GetAttribute("href"));//获取点击中的链接地址
二、WebBrowser常用事件处理:
.Navigated += new WebBrowserNavigatedEventHandler(WebBrowser_Navigated);//加载中处理事件.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser _DocumentCompleted);//页面加载完成处理事件.NewWindow += new CancelEventHandler(WebBrowser _NewWindow);//新的窗口中打开页面
三、事件处理函数
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
相信本文所述对大家C#程序设计的学习有一定的借鉴价值。
新闻热点
疑难解答