C#之WinForm WebBrowser實用技巧匯總
本文實例匯總了C#中WinForm WebBrowser常見的實用技巧,對于C#程序開發(fā)來說有不錯的借鑒價值。分別敘述如下:
方法1:獲取狀態(tài)欄信息
void webBrowser1_StatusTextChanged(object sender, EventArgs e)
{
label1.Text = webBrowser1.StatusText;
}
方法2:頁面跳轉后改變地址欄地址
//在Navigated事件處理函數(shù)中改變地址欄地址是最恰當?shù)模?
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
textBox1.Text = webBrowser1.Url.ToString();
}
方法3:設置單選框
//建議使用執(zhí)行單擊事件的方式來設置單選框,而不是修改屬性:
webBrowser1.Document.GetElementById("RBT_A").InvokeMember("click");
方法4:設置聯(lián)動型下拉列表
//比較常見的聯(lián)動型多級下拉列表就是省/市縣選擇了,這種情況下直接設置選擇項的屬性不會觸發(fā)聯(lián)動,需要在最后執(zhí)行觸發(fā)事件函數(shù)才能正常工作:
foreach (HtmlElement f in s.GetElementsByTagName("option"))
{
if (f.InnerText == "北京")
{
f.SetAttribute("selected", "selected");
}
else
{
f.SetAttribute("selected", "");
}
}
s.RaiseEvent("onchange");
方法5:在WinForm中響應Web事件
假設HTML源代碼如下:
<html> <body> <input type="button" id="btnClose" value="關閉" /> </body> </html>
HtmlDocument htmlDoc = webBrowser.Document;
HtmlElement btnElement = htmlDoc.All["btnClose"];
if (btnElement != null)
{
btnElement.click += new HtmlElementEventHandler(HtmlBtnClose_Click);
}
很簡單吧?那么稍稍高級一點的——我們都知道一個HTML元素可能有很多各種各樣的事件,而HtmlElement這個類只給出最常用、共通的幾個。那么,如何響應其他事件呢?這也很簡單,只需要調(diào)用HtmlElement的AttachEventHandler就可以了:
btnElement.AttachEventHandler("onclick", new EventHandler(HtmlBtnClose_Click));
這一句等價于上面的btnElement.click += new HtmlElementEventHandler(HtmlBtnClose_Click);
對于其他事件,把"onclick"換成該事件的名字就可以了。例如:
formElement.AttachEventHandler("onsubmit", new EventHandler(HtmlForm_Submit));
方法6:模擬表單自動填寫和提交
假設有一個最簡單的登錄頁面,輸入用戶名密碼,點“登錄”按鈕即可登錄。已知用戶名輸入框的id(或Name,下同)是username,密碼輸入框的id是password,“登錄”按鈕的id是submitbutton,那么我們只需要在webBrowser的DocumentCompleted事件中使用下面的代碼即可:
HtmlElement btnSubmit = webBrowser.Document.All["submitbutton"];
HtmlElement tbUserid = webBrowser.Document.All["username"];
HtmlElement tbPasswd = webBrowser.Document.All["password"];
if (tbUserid == null || tbPasswd == null || btnSubmit == null)
return;
tbUserid.SetAttribute("value", "smalldust");
tbPasswd.SetAttribute("value", "12345678");
btnSubmit.InvokeMember("click");
關于表單的提交,的確還有另一種方法就是獲取form元素而不是button,并用form元素的submit方法:
HtmlElement formLogin = webBrowser.Document.Forms["loginForm"];
//……
formLogin.InvokeMember("submit");
本文之所以沒有推薦這種方法,是因為現(xiàn)在的網(wǎng)頁,很多都在submit按鈕上添加onclick事件,以對提交的內(nèi)容做最基本的驗證。如果直接使用form的submit方法,這些驗證代碼就得不到執(zhí)行,有可能會引起錯誤。
方法7:調(diào)用腳本
首先是調(diào)用Web頁面的腳本中已經(jīng)定義好的函數(shù)。假設HTML中有如下Javascript:
function DoAdd(a, b) {
return a + b;
}
那么,我們要在WinForm調(diào)用它,只需如下代碼即可:
object oSum = webBrowser.Document.InvokeScript("DoAdd", new object[] { 1, 2 });
int sum = Convert.ToInt32(oSum);
其次,如果我們想執(zhí)行一段Web頁面中原本沒有的腳本,該怎么做呢?這次.Net的類沒有提供,看來還要依靠COM了。IHTMLWindow2可以將任意的字符串作為腳本代碼來執(zhí)行。
string scriptline01 = @"function ShowPageInfo() {";
string scriptline02 = @" var numLinks = document.links.length; ";
string scriptline03 = @" var numForms = document.forms.length; ";
string scriptline04 = @" var numImages = document.images.length; ";
string scriptline05 = @" var numScripts = document.scripts.length; ";
string scriptline06 = @" alert('網(wǎng)頁的統(tǒng)計結果:\r\n鏈接數(shù):' + numLinks + ";
string scriptline07 = @" '\r\n表單數(shù):' + numForms + ";
string scriptline08 = @" '\r\n圖像數(shù):' + numImages + ";
string scriptline09 = @" '\r\n腳本數(shù):' + numScripts);}";
string scriptline10 = @"ShowPageInfo();";
string strScript = scriptline01 + scriptline02 + scriptline03 + scriptline04 + scriptline05 +
scriptline06 + scriptline07 + scriptline08 + scriptline09 + scriptline10;
IHTMLWindow2 win = (IHTMLWindow2)webBrowser.Document.Window.DomWindow;
win.execScript(strScript, "Javascript");
最后:在腳本中調(diào)用WinForm里的代碼,這個可能嗎? 呵呵,當然是可能的。
下面的代碼示例演示如何使用 ObjectForScripting 屬性。在該示例中,ObjectForScripting 屬性被設置為當前窗體。
using System;
using System.Windows.Forms;
using System.Security.Permissions;
[PermissionSet(SecurityAction.Demand, Name="FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class Form1 : Form
{
private WebBrowser webBrowser1 = new WebBrowser();
private Button button1 = new Button();
[STAThread]
public static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
public Form1()
{
button1.Text = "call script code from client code";
button1.Dock = DockStyle.Top;
button1.Click += new EventHandler(button1_Click);
webBrowser1.Dock = DockStyle.Fill;
Controls.Add(webBrowser1);
Controls.Add(button1);
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.AllowWebBrowserDrop = false;
webBrowser1.IsWebBrowserContextMenuEnabled = false;
webBrowser1.WebBrowserShortcutsEnabled = false;
webBrowser1.ObjectForScripting = this;
// Uncomment the following line when you are finished debugging.
//webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.DocumentText =
"<html><head><script>" +
"function test(message) { alert(message); }" +
"</script></head><body><button " +
"onclick=\"window.external.Test('called from script code')\">" +
"call client code from script code</button>" +
"</body></html>";
}
public void Test(String message)
{
MessageBox.Show(message, "client code");
}
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("test",
new String[] { "called from client code" });
}
}
//該代碼實例源于:MSDN
相信本文所述實例對大家的C#程序設計有一定的借鑒價值。
相關文章
C#操作圖片讀取和存儲SQLserver實現(xiàn)代碼
用C#將Image轉換成byte[]并插入數(shù)據(jù)庫/將圖片數(shù)據(jù)從SQLserver中取出來并顯示到pictureBox控件上,接下來將為你詳細介紹下實現(xiàn)步驟,感興趣的你可以參考下2013-03-03

