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

这篇关于c#控制IE浏览器自动点击等事件WebBrowser,mshtml.IHTMLDocument2的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/682244

相关文章

基于Python开发Windows屏幕控制工具

《基于Python开发Windows屏幕控制工具》在数字化办公时代,屏幕管理已成为提升工作效率和保护眼睛健康的重要环节,本文将分享一个基于Python和PySide6开发的Windows屏幕控制工具,... 目录概述功能亮点界面展示实现步骤详解1. 环境准备2. 亮度控制模块3. 息屏功能实现4. 息屏时间

CSS place-items: center解析与用法详解

《CSSplace-items:center解析与用法详解》place-items:center;是一个强大的CSS简写属性,用于同时控制网格(Grid)和弹性盒(Flexbox)... place-items: center; 是一个强大的 css 简写属性,用于同时控制 网格(Grid) 和 弹性盒(F

CSS实现元素撑满剩余空间的五种方法

《CSS实现元素撑满剩余空间的五种方法》在日常开发中,我们经常需要让某个元素占据容器的剩余空间,本文将介绍5种不同的方法来实现这个需求,并分析各种方法的优缺点,感兴趣的朋友一起看看吧... css实现元素撑满剩余空间的5种方法 在日常开发中,我们经常需要让某个元素占据容器的剩余空间。这是一个常见的布局需求

CSS Anchor Positioning重新定义锚点定位的时代来临(最新推荐)

《CSSAnchorPositioning重新定义锚点定位的时代来临(最新推荐)》CSSAnchorPositioning是一项仍在草案中的新特性,由Chrome125开始提供原生支持需... 目录 css Anchor Positioning:重新定义「锚定定位」的时代来了! 什么是 Anchor Pos

CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比

《CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比》CSS中的position属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布... css 中的 position 属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布局和层叠关

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

一文详解MySQL如何设置自动备份任务

《一文详解MySQL如何设置自动备份任务》设置自动备份任务可以确保你的数据库定期备份,防止数据丢失,下面我们就来详细介绍一下如何使用Bash脚本和Cron任务在Linux系统上设置MySQL数据库的自... 目录1. 编写备份脚本1.1 创建并编辑备份脚本1.2 给予脚本执行权限2. 设置 Cron 任务2

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

HTML5 搜索框Search Box详解

《HTML5搜索框SearchBox详解》HTML5的搜索框是一个强大的工具,能够有效提升用户体验,通过结合自动补全功能和适当的样式,可以创建出既美观又实用的搜索界面,这篇文章给大家介绍HTML5... html5 搜索框(Search Box)详解搜索框是一个用于输入查询内容的控件,通常用于网站或应用程

CSS3中的字体及相关属性详解

《CSS3中的字体及相关属性详解》:本文主要介绍了CSS3中的字体及相关属性,详细内容请阅读本文,希望能对你有所帮助... 字体网页字体的三个来源:用户机器上安装的字体,放心使用。保存在第三方网站上的字体,例如Typekit和Google,可以link标签链接到你的页面上。保存在你自己Web服务器上的字