在WiinForm使用WebBrowser控件的過程中,常常會被目标網頁上彈出的alert、confirm等對話框打斷工作流程。google了一下,發現有人采用定時器自動送Enter,也有人采用FindWindow等方法來進行自動關閉,其實,我們隻需要在目标網頁上執行一段腳本就可以了。
//禁用目标window的confirm、alert等對話框。
private void disableConfirm()
{
HtmlDocument doc = webBrowser1.Document.Window.Frames["mainFrame"].Document;
//架構結構中,必須正确的指定目标架構
IHTMLWindow2 win = (IHTMLWindow2)doc.Window.DomWindow;
string s = @"function confirm() {";
s += @"return true;";
s += @"}";
s += @"function alert() {}";
win.execScript(s, "javascript");
}
為了使用IHTMLWindow2接口,必須的添加對非托管COM對象的托管包裝,在VS2005中很簡單,隻需要在項目引用裡面選擇COM頁籤,添加Microsoft HTML Object Library即可,路徑為C:/Windows|System32/MSHTML.TLB。在CS檔案裡面引入托管包裝的命名空間mshtml即可。
using mshtml;
存取網頁的DOM元素:
HtmlElement euser = webBrowser1.Document.All["txtUserName"];
HtmlElement bSubmit = webBrowser1.Document.All["Button1"];
euser.SetAttribute("value","想設定的值"); //設定DOM元素value屬性
bSubmit.InvokeMember("click"); //激發該元素的click事件