.NET 获取任意一个WebBrowser中的HTMLDocument信息

来源:互联网 发布:网络电影票房排行 编辑:程序博客网 时间:2024/05/29 15:28

首先必须找到索要获取的WebBrowser句柄

然后

using System;using System.Collections.Generic;using System.Text;using System.Runtime.InteropServices;using mshtml;namespace Test{     public partial class Form1     {         #region AA         [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]         static extern uint RegisterWindowMessage(string lpString);         [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]         public static extern IntPtr SendMessageTimeout(         IntPtr windowHandle,         uint Msg,         IntPtr wParam,         IntPtr lParam,         SendMessageTimeoutFlags flags,         uint timeout,         out IntPtr result);         [DllImport("oleacc.dll", PreserveSig = false)]         [return: MarshalAs(UnmanagedType.Interface)]         static extern object ObjectFromLresult(IntPtr lResult,         [MarshalAs(UnmanagedType.LPStruct)] Guid refiid, IntPtr wParam);         [Flags]         public enum SendMessageTimeoutFlags : uint         {             SMTO_NORMAL = 0x0,             SMTO_BLOCK = 0x1,             SMTO_ABORTIFHUNG = 0x2,             SMTO_NOTIMEOUTIFNOTHUNG = 0x8         }         public delegate bool EnumWindowsProc(IntPtr hWnd, ref IntPtr lParam);         public static IHTMLDocument2 GetHtmlDocument(IntPtr hWnd)         {             IntPtr hWndChild = hWnd;             //注册窗口信息             uint uMsg = RegisterWindowMessage("WM_HTML_GETOBJECT");             //定义hRes指针             IntPtr hRes;             //发送消息超时时间             SendMessageTimeout(hWndChild, uMsg, IntPtr.Zero, IntPtr.Zero, SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 1000, out hRes);             //如果hRes为空指针则返回空             if (hRes.ToInt32() == 0) return null;             IHTMLDocument2 doc = ObjectFromLresult(hRes, typeof(IHTMLDocument2).GUID, IntPtr.Zero) as IHTMLDocument2;             return doc;         }         #endregion     }}