通过IE句柄 获得 IE Document对象和IWebBrowser2对象

来源:互联网 发布:vb 表格控件 编辑:程序博客网 时间:2024/04/30 09:37

 http://blog.csdn.net/stxyc/article/details/5411360

http://hi.baidu.com/lxxgfc/blog/item/9070103dc7f3c4f614cecb30.html

本来是做JAVA的,由于工作需要,最近做了一些C# 对网页的控制, 
一直以来都是利用System.Windows.Forms.WebBrowser webBrowser1 来把网页嵌入到我的窗体内进行控制。而且控制起来非常方便。 
  有一个项目的网页比较特殊,目前我还不知道什么原因,他的网页会把我的程序挂起,没办法,只有利用跨进程获得IE对象了。 
  主要应用了 一个COM组件 三个引用 三个对象 来讲述这个简单的例子 
1.COM组件 Microsoft.mshtml.dll 这个不用多说了,地球人都知道。 
2.     using mshtml;//这。。。。。多说无用 
  using SHDocVw; //IWebBrowser2 是他下面的 
        using System.Runtime.InteropServices; //DLL的引用,方法的重写3.IWebBrowser2 其实他要比WebBrowser 强大的多,正常我们直接用内嵌的浏览器对象,如果深入的朋友,在应用内嵌浏览器的时候也可以使用它来接受对象。 
IShellWindows 呵呵。。。自己追踪下 就知道了。。都不用查 
HTMLDocumentClass 这个本人也不求甚解,只知道他和 HTMLDocument差不多,只是方法名不太一样。。。 
//--------------------------------------------------------------------------------- 
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Text; 
using System.Windows.Forms; 
using mshtml; 
using SHDocVw; 
using System.Runtime.InteropServices;namespace dxzj 
{ 
    public partial class Form1 : Form 
    { 
        [DllImport("user32", EntryPoint = "FindWindow")] 
        public static extern int FindWindowA(string lpClassName, string lpWindowName); 
        public Form1() 
        { 
            InitializeComponent(); 
        }        private void timer1_Tick(object sender, EventArgs e) 
        {        } 
        //声明Document对象(如果用内嵌浏览器,我们得到的是一个HTMLDocument) 
        HTMLDocumentClass document = null; 
        private void button1_Click(object sender, EventArgs e) 
        { 
            //查找打开的窗口句柄 
            int iehwnd = FindWindowA(null, "用银行卡充值_中国联通 - Microsoft Internet Explorer"); 
            //初始化所有IE窗口 
            IShellWindows sw = new ShellWindowsClass(); 
            //轮询所有IE窗口 
            for (int i = sw.Count - 1; i >= 0; i--) 
            { 
                //得到每一个IE的 IWebBrowser2 对象 
                IWebBrowser2 iwb2 = sw.Item(i) as IWebBrowser2; 
                //比对 得到的 句柄是否符合查找的窗口句柄 
                if(iwb2.HWND == iehwnd) 
                { 
                    //查找成功 进行赋值 
                    document = (HTMLDocumentClass)iwb2.Document; 
                    //对网页进行操作 
                    document.getElementById("directOnlinePayInfo.productNO").innerText = "1111"; 
                } 
            } 
        } 
    } 
}