1. 程式人生 > >c#控制IE瀏覽器自動點選等事件WebBrowser,mshtml.IHTMLDocument2

c#控制IE瀏覽器自動點選等事件WebBrowser,mshtml.IHTMLDocument2

可以實現例如通過應用程式操作google搜尋,使用者輸入要搜尋的內容,然後在google中搜索;可以自動點選網頁上的按鈕等功能


    1. 加入對Microsoft Internet Controls的引用;
    2. 加入對Microsoft HTML Object Library的引用;


(要引入Microsoft.mshtml.dll 地址是C:\Program Files\Microsoft.NET\Primary Interop Assemblies)
    3. 通過mshtml.IHTMLDocument2、SHDocVw.InternetExplorer、SHDocVw.ShellWindowsClass獲取當前開啟的google搜尋頁面的IE視窗控制代碼;
    4. 根據3返回的控制代碼,獲得當前開啟的google頁面的mshtml.IHTMLDocument2物件;
    5. 根據4返回的IHTMLDocument2物件,獲得搜尋輸入框和提交按鈕(可檢視google頁面原始檔,確認輸入框和提交按鈕的型別和名字);
    6. 在搜尋輸入框中輸入要搜尋的內容,並執行提交按鈕的click動作即可進行搜尋;


 


簡單來說:


開啟ie:


SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass();
object objFlags = 1;
object objTargetFrameName = "";
object objPostData = "";
object objHeaders = "";
SHDocVw.InternetExplorer webBrowser1= (SHDocVw.InternetExplorer)shellWindows.Item(shellWindows.Count-1);
webBrowser1.Navigate(“http://www.google.cn”, ref objFlags, ref objTargetFrameName, ref objPostData, ref objHeaders);


(可以簡略點寫:object c=null; myWeb.Navigate("http://zhidao.baidu.com/",ref c,ref c,ref c,ref c); )
mshtml.IHTMLDocument2 htmlDoc = webBrowser1.Document as mshtml.IHTMLDocument2;


 


//...獲取WebBroswer中的body程式碼
mshtml.HTMLDocumentClass doc=(mshtml.HTMLDocumentClass)myWeb.Document;
mshtml.HTMLBody body=(mshtml.HTMLBody)docCC.body;
string html=body.innerHTML.ToString();
//...如果裡面有Form,要給裡面的text填充資訊
mshtml.IHTMLDocument2 doc2=(mshtml.IHTMLDocument2)myWeb.Document;
mshtml.IHTMLElementCollection inputs;
inputs=(mshtml.IHTMLElementCollection)doc2.all.tags("INPUT");
mshtml.IHTMLElement element=(mshtml.IHTMLElement)inputs.item("userName",0);
mshtml.IHTMLInputElement inputElement=(mshtml.IHTMLInputElement)element;
inputElement.value="填充資訊";
//...要點選裡面的某個按鈕
mshtml.IHTMLDocument2 doc2=(mshtml.IHTMLDocument2)myWeb.Document;
mshtml.IHTMLElementCollection inputs;
inputs=(mshtml.IHTMLElementCollection)doc2.all.tags("INPUT");
mshtml.IHTMLElement element=(mshtml.IHTMLElement)inputs.item("SubmitBut",0);
element.click();


 


1、根據元素ID獲取元素的值。


比如要獲取<img class="" id="regimg" src="/register/checkregcode.html?1287068791" width="80" height="22">這個標籤裡的src屬性的值:


mshtml.IHTMLDocument2 doc2 = (mshtml.IHTMLDocument2)webBrowser1.Document;
mshtml.IHTMLElement img = (mshtml.IHTMLElement)doc2.all.item("regimg", 0);


string imgUrl = (string)img.getAttribute("src");


2、填寫表單,並確定


mshtml.IHTMLElement loginname = (mshtml.IHTMLElement)doc2.all.item("loginname", 0);
    mshtml.IHTMLElement loginPW = (mshtml.IHTMLElement)doc2.all.item("password", 0);
    mshtml.IHTMLElement loginBT = (mshtml.IHTMLElement)doc2.all.item("formsubmit", 0);
    mshtml.IHTMLElement loginYZ = (mshtml.IHTMLElement)doc2.all.item("regcode", 0);
    loginname.setAttribute("value", tbLoginName.Text);
    loginPW.setAttribute("value", tbLoginPassWord.Password);
    loginYZ.setAttribute("value", tbYZ.Text);
    loginBT.click();


3、獲取原始碼


textBox1.Text = doc2.body.innerHTML;


4、執行JS


mshtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)doc2.parentWindow;
win.execScript("changeRegImg()", "javascript");//使用JS


5、禁止JS,WPF下目前發現唯一適用的一種方法:


public void HideScriptErrors(WebBrowser wb, bool Hide)
   {


    FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);


    if (fiComWebBrowser == null) return;


    object objComWebBrowser = fiComWebBrowser.GetValue(wb);


    if (objComWebBrowser == null) return;


    objComWebBrowser.GetType().InvokeMember(


    "Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { Hide });


   }


   void webBrowser1_Navigated(object sender, NavigationEventArgs e)
   {


    HideScriptErrors(webBrowser1,


    true);


   }


 


 


 


下面是另外一遍部落格裡寫的比較好的


#region Search    
        public static void Search(string searchText)   
        {   
            SHDocVw.InternetExplorer ieWnd = GetIEWndOfGoogle();   
            mshtml.IHTMLDocument2 ieDoc = GetIEDocOfGoogle(ref ieWnd);   
  
            System.Diagnostics.Trace.Assert(ieDoc != null);   
            SearchTextInGoogle(ieDoc, searchText);   
  
            //activate ie window    
            SetForegroundWindow(ieWnd.HWND);               
        }   
        #endregion   
 
        #region get ie window of google page    
        public static SHDocVw.InternetExplorer GetIEWndOfGoogle()   
        {   
            mshtml.IHTMLDocument2 ieDoc;   
            SHDocVw.InternetExplorer ieWnd = null;   
            SHDocVw.ShellWindowsClass shellWindows = new SHDocVw.ShellWindowsClass();   
  
            foreach (SHDocVw.InternetExplorer ie in shellWindows)   
            {   
                //if it is ie window    
                if (ie.FullName.ToUpper().IndexOf("IEXPLORE.EXE") > 0)   
                {   
                    //get the document displayed    
                    ieDoc = (mshtml.IHTMLDocument2)ie.Document;   
                    if (ieDoc.title.ToUpper().IndexOf("GOOGLE") >= 0)   
                    {   
                        ieWnd = ie;   
                        break;   
                    }   
                }   
            }   
               
            shellWindows = null;   
  
            return ieWnd;   
        }   
        #endregion   
 
        #region get ie document of google page    
        public static mshtml.IHTMLDocument2 GetIEDocOfGoogle(ref SHDocVw.InternetExplorer ieWnd)   
        {   
            object missing = null;   
            mshtml.IHTMLDocument2 ieDoc;   
  
            if (ieWnd == null)   
            {   
                ieWnd = new SHDocVw.InternetExplorer();   
                ieWnd.Visible = true;   
                ieWnd.Navigate("http://www.google.com", ref missing, ref missing, ref missing, ref missing);   
  
                //wait for loading completed, or using DocumentComplete Event    
                while (ieWnd.StatusText.IndexOf("完成") == -1)   
                    Application.DoEvents();   
            }   
  
            ieDoc = (mshtml.IHTMLDocument2)ieWnd.Document;   
            return ieDoc;   
        }   
        #endregion
#region Search the given text in google    
        ///// <summary>    
        /// search the given text in google home page    
        /// we can see the source file of google home page to confirm the elements we need    
        /// the html file of google home page is as follows    
        ///     
        /// <table cellpadding=0 cellspacing=0>    
        ///     <tr valign=top>    
        ///         <td width=25%> </td>    
        ///         <td align=center nowrap>    
        ///             <input name=hl type=hidden value=zh-CN>    
        ///             <input autocomplete="off" maxlength=2048 name=q size=55 title="Google 搜尋" value="">    
        ///             <br>    
        ///             <input name=btnG type=submit value="Google 搜尋">    
        ///             <input name=btnI type=submit value=" 手氣不錯 ">    
        ///         </td>    
        ///         ...    
        ///// </summary>            
        public static void SearchTextInGoogle(mshtml.IHTMLDocument2 ieDoc, string searchText)   
        {   
            mshtml.HTMLInputElementClass input;   
  
            //set the text to be searched    
            foreach (mshtml.IHTMLElement ieElement in ieDoc.all)   
            {   
                //if its tag is input and name is q(question)    
                if (ieElement.tagName.ToUpper().Equals("INPUT"))   
                {   
                    input = ((mshtml.HTMLInputElementClass)ieElement);   
                    if (input.name == "q")   
                    {   
                        input.value = searchText;   
                        break;   
                    }   
                }   
            }   
  
            //click the submit button to search    
            foreach (mshtml.IHTMLElement ieElement in ieDoc.all)   
            {   
                //if its tag is input    
                if (ieElement.tagName.ToUpper().Equals("INPUT"))   
                {   
                    input = (mshtml.HTMLInputElementClass)ieElement;   
                    if (input.name == "btnG")   
                    {   
                        input.click();   
                        break;   
                    }   
                }   
            }   
        }   
        #endregion 




 


參考文章:


http://blog.csdn.net/livelylittlefish/archive/2008/08/25/2829873.aspx


http://hi.baidu.com/andyleesoft/blog/item/802e02289fcc1f94023bf66a.html


http://zhidao.baidu.com/question/48084010.html


 


另外一個例子


IHTMLDocument2 doc = webbrowser.Document.DomDocument as IHTMLDocument2;
IHTMLBodyElement bodyElement = doc.body as IHTMLBodyElement;
if (bodyElement != null)
{


        IHTMLTxtRange range = bodyElement.createTextRange();
        HTMLDocumentClass documentClass = wb1.Document.DomDocument as HTMLDocumentClass;
        IHTMLElement caret_pos = documentClass.getElementById("caret_pos");
        if (caret_pos != null)
       {
               range.moveToElementText(caret_pos);
               range.select();
        }
}


 


2011-3-14新增


給html元素新增事件


IHTMLElement ieElement = .......


((mshtml.HTMLElementEvents2_Event)ieElement).onclick += new mshtml.HTMLElementEvents2_onclickEventHandler(this.element_onClick);


 


public bool element_onClick(mshtml.IHTMLEventObj e)
{。。。。}


要在程式中出發html中的事件,這個想用什麼eventhandler之類的,搞了半天都沒有研究出來,資料又搜不到,最後用執行js的方法實現之:


js觸發事件:


var oEvent = document.createEventObject();


document.getElementById('addrCity').fireEvent('onchange', oEvent);