using mshtml; /// <summary> /// 返回指定Url的IE窗口下的 IHTMLDocument2 对象。 /// </summary> /// <returns>IHTMLDocument2</returns> public mshtml.IHTMLDocument2 GetIHTMLDocument2ByUrl(string url) { SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass(); foreach (SHDocVw.InternetExplorer ie in shellWindows) { string filename = System.IO.Path.GetFileNameWithoutExtension(ie.FullName).ToLower(); if (filename.Equals("iexplore")) { if (ie.LocationURL == url) { mshtml.IHTMLDocument2 htmlDoc = ie.Document as mshtml.IHTMLDocument2; MessageBox.Show(ie.LocationURL); //MessageBox.Show( (htmlDoc != null) ? htmlDoc.body.outerHTML : "***Failed***"); return htmlDoc; } } } return null; } private void button2_Click(object sender, EventArgs e) { mshtml.IHTMLDocument2 iHTMLDocument2 = GetIHTMLDocument2ByUrl("http://www.163.com/"); iHTMLDocument2.parentWindow.execScript("alert('ad');", "JavaScript"); HTMLDocumentClass obj = (HTMLDocumentClass)iHTMLDocument2; IHTMLElement iHTMLElement = null; IHTMLElementCollection c = obj.getElementsByTagName("input"); foreach (IHTMLElement el in c) { if (el.outerHTML.IndexOf("登录") != -1) { iHTMLElement = el; break; } } if (iHTMLElement != null) { iHTMLElement.click(); // 点击登录按钮 } } function GetBindedFieldValue: WideString; var Ws:WideString; JSFn: string; begin JSFn := 'GetBindedFieldValue()'; RunScript(JSFn); Ws := OleVariant(wb.Document).script.BindFieldValues; result := Ws; end; function RunScript(const JSFn:string):integer; var Doc: IHTMLDocument2; HTMLWindow: IHTMLWindow2; begin result := 0; Doc:=wb.Document as IHTMLDocument2; if not Assigned(Doc) then Exit; HTMLWindow := Doc.parentWindow; if not Assigned(HTMLWindow) then Exit; // Run JavaScript try HTMLWindow.execScript(JSFn, 'JavaScript'); // execute function except result := -1; end; end;