C#通过应用程序打开google进行搜索

IE编程——通过应用程序打开google并进行搜索

    通过应用程序操作google搜索,用户输入要搜索的内容,然后在google中搜索;若开始时并没有IE实例运行,则打开一个默认的IE。  

    1. 加入对Microsoft Internet Controls的引用;

    2. 加入对Microsoft HTML Object Library的引用;

    3. 通过mshtml.IHTMLDocument2、SHDocVw.InternetExplorer、SHDocVw.ShellWindowsClass获取当前打开的google搜索页面的IE窗口句柄;

    4. 根据3返回的句柄,获得当前打开的google页面的mshtml.IHTMLDocument2对象;

    5. 根据4返回的IHTMLDocument2对象,获得搜索输入框和提交按钮(可查看google页面源文件,确认输入框和提交按钮的类型和名字);

    6. 在搜索输入框中输入要搜索的内容,并执行提交按钮的click动作即可进行搜索;

 

    注:本文测试在中文系统下,若在其他语言系统下,需修改StatusText的判断。

 

    几个对象和接口的简单解释:

 

    1. ShellWindows Object
          The ShellWindows object represents a collection of the open windows that belong to the Shell. Methods are provided that can be used to control and execute commands within the Shell. There are also methods that can be used to obtain other Shell-related objects.

    2. InternetExplorer Object

          Controls a remote instance of Microsoft Internet Explorer through Automation.

 

    3. IHTMLDocument2 Interface

          Stock Implementation: mshtml.dll

          Inherits from: IDispatch interface

          Header and IDL files: Mshtml.h, Mshtml.idl

          This interface retrieves information about the document, and examines and modifies the HTML elements and text within the document.

          Typically, every window object has a corresponding document object that you can retrieve by calling the QueryInterface method with the IID_IHTMLDocument or IID_IHTMLDocument2 interface identifiers. Windows that contain HTML documents always have valid document objects, but windows that contain documents in other formats might not.

 

    4. IHTMLInputElement Interface
          Stock Implementation: mshtml.dll

          Inherits from: IDispatch interface

          Header and IDL files: Mshtml.h, Mshtml.idl 


          This interface specifies any type of input control.

    5. IHTMLElement Interface
          Stock Implementation: mshtml.dll

          Inherits from: IDispatch interface

          Header and IDL files: Mshtml.h, Mshtml.idl 


          This interface provides the ability to programmatically access the properties and methods that are common to all element objects.

 

     具体解释可参考msdn。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices;

namespace TestAutoSearchInGoogle
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        private void exitBtn_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void searchBtn_Click(object sender, EventArgs e)
        {
            if(searchText.Text.Equals(""))
            {
                MessageBox.Show("please input the search text", "information prompt");
                return;
            }
            AutoSearchInGoogle.Search(searchText.Text);
        }
    }

    public class AutoSearchInGoogle
    {
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int SetForegroundWindow(int hwnd); 

        #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="&nbsp;手气不错&nbsp;"> 
        ///         </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 
    }
}

输入DirectUIHWND,搜索结果如下:

C#通过应用程序打开google进行搜索

来源:http://blog.csdn.net/livelylittlefish/article/details/2829873

加支付宝好友偷能量挖...


评论(0)网络
阅读(122)喜欢(0)Asp.Net/C#/WCF