扩大
缩小

WebBrowser使用例子

本文参考了:http://www.cnblogs.com/txw1958/archive/2012/09/24/CSharp-WebBrowser.html

在上文的基础上加入了 一些处理弹出对话框的处理。

1.获取非input元素的值(3种)

webBrowser1.Document.All["控件ID"].InnerText;
webBrowser1.Document.GetElementById("控件ID").InnerText;
webBrowser1.Document.GetElementById("控件ID").GetAttribute("value");

 

2.获取input元素的值(2种)

webBrowser1.Document.All["控件ID"].GetAttribute("value");;
webBrowser1.Document.GetElementById("控件ID").GetAttribute("value");

 3.给输入框赋值(3种)

userName.InnerText = "myname";
webBrowser1.Document.GetElementById("userName").SetAttribute("value", "myUserId");

 

4.下拉框

xialaElement.SetAttribute("value", "abc"); 

 

5.复选框

fuxuankuangElement.SetAttribute("checked", "true");

6.多选框

duoxuankuangElement.SetAttribute("checked", "checked");

7.根据已有ID的元素找到没有ID的元素

yizhiElement.Parent.Parent.Parent.Parent.FirstChild.FirstChild.Children[1];

8.模拟元素点击

btn1.InvokeMember("click");//执行按扭操作

9.模拟元素双击

btn1.InvokeMember("click");//执行按扭操作
btn1.InvokeMember("click");//执行按扭操作

10.获取页面的后台ajax,js 后台加载的元素

this.timer1.Enabled = true; //设置计时器开始
this.timer1.Interval = 1000 * 2;//设置2s 间隔执行一次

private void timerForConfirmReceipt_Tick(object sender, EventArgs e)
{
   Document = this.webbrowser.Document;
if (Document != null && Document.Body != null) { foreach (HtmlElement element in Document.Body.All) { if (element.TagName.ToLower().Equals("table")) { foreach (HtmlElement child in element.GetElementsByTagName("a")) { if (child.InnerText.Contains("确认收货")) { this.timerForConfirmReceipt.Enabled = false;//有这个元素的时候才关闭计时器,没有的话不能关闭,等待下次计时器进入这个函数。 child.InvokeMember("click"); return; } } } } } }

 11.屏蔽脚本错误

private void MainFrm_Load(object sender, EventArgs e)
        {
            webBrowser1.ScriptErrorsSuppressed = true;
        }

12.自动点击简单的弹出提示框

private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
  //自动点击弹出确认或弹出提示
  IHTMLDocument2 vDocument = (IHTMLDocument2)webBrowser1.Document.DomDocument;
  vDocument.parentWindow.execScript("function confirm(str){return true;} ", "javascript"); //弹出确认
  vDocument.parentWindow.execScript("function alert(str){return true;} ", "javaScript");//弹出提示
//上面代码可以写在窗体load函数中去。
}

13.点击网页弹出的下载框

 // 先将所有的句柄那输出到文本文件中, 或者使用vc 的工具的spy ++ 查看
            StreamWriter sw = new StreamWriter(@"D:\windowname.txt", true);
            foreach (WindowInfo info in Win32ApiWrapper.GetAllDesktopWindows())
            {
                sw.WriteLine(info.hWnd + "\t" + info.SzWindowName + "\t" + info.SzClassName);
                foreach (WindowInfo itemInfo in Win32ApiWrapper.GetChildWindowsByParentHwnd(info.hWnd))
                {
                    sw.WriteLine("\t\t"+info.SzWindowName + "\t\t" + itemInfo.hWnd + "\t" + itemInfo.SzWindowName + "\t" + itemInfo.SzClassName);
                }


            }
            sw.Close();//可以查看这个具体的窗口句柄, 明明有的窗口句柄如果没有捕获到,请使用计时器。

            var win =
Win32ApiWrapper.GetAllDesktopWindows().FirstOrDefault(r => r.SzWindowName.Contains("文件下载"));//找到窗口标题为文件下载的句柄
            if (win != null)
            {
                this.timerForWaitDownloadBox.Enabled = false;
                IntPtr vHandles = webBrowser1.Handle;
                vHandles = WinAPI.GetChildHandle(vHandles, IntPtr.Zero, "Shell Embedding");
                vHandles = WinAPI.GetChildHandle(vHandles, IntPtr.Zero, "Shell DocObject View");
                vHandles = WinAPI.GetChildHandle(vHandles, IntPtr.Zero, "Internet Explorer_Server");
                 
                var passwordCtrl = Win32ApiWrapper.GetChildWindowsByParentHwnd(win.hWnd)
                    .FirstOrDefault(
                        r => r.SzClassName == "Button" && r.SzWindowName.Contains("打开"));//找到文件下载的打开按钮句柄
                if (passwordCtrl != null)
                {
                    
                    //获得焦点
                    IntPtr hwnd_top = IntPtr.Zero;
                    uint swp_NoMovie = 2;
                    uint swp_NOSIZE = 1;
                    uint swp_NOACTIVATE = 0x10;
                    uint swp_SHOWWINDOW = 0x40;
                    Win32ApiWrapper.SetWindowPos(passwordCtrl.hWnd, hwnd_top, 0, 0, 0, 0, swp_NoMovie | swp_NOSIZE | swp_NOACTIVATE | swp_SHOWWINDOW);
                    Win32ApiWrapper.SendMessage(passwordCtrl.hWnd, Win32ApiWrapper.WM_LBUTTONDOWN, IntPtr.Zero, "");
                    Win32ApiWrapper.SendMessage(passwordCtrl.hWnd, Win32ApiWrapper.WM_LBUTTONUP, IntPtr.Zero, "");
                    Application.DoEvents();
                    SendKeys.Flush();
                 
                    SendKeys.Send("{TAB}");//发送一个tab 按钮, 切换到下载弹出框的保存按钮上, 
                    SendKeys.Flush();//处理发送信息
                    SendKeys.Send("{ENTER}");//在发送一个enter按钮
                    SendKeys.Flush();
                    this.timerForSaveFile.Enabled = true;//启动一个保存选择文件对话框, 进行后续处理

WinAPI.cs文件

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;

namespace Test
{
     static class WinAPI
    {
        public  const int WM_KEYDOWN = 0X100;
        public  const int WM_KEYUP = 0X101;
        public  const int WM_SYSCHAR = 0X106;
        public  const int WM_SYSKEYUP = 0X105;
        public  const int WM_SYSKEYDOWN = 0X104;
        public  const int WM_CHAR = 0X102;


        #region WinodwsAPI
        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private static extern IntPtr FindWindow(string IpClassName, string IpWindowName);

        [DllImport("user32.dll", EntryPoint = "FindWindowEx")]
        private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);

        [DllImport("User32.DLL")]
        public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
        public static int IDM_VIEWSOURCE = 2139;
        public static uint WM_COMMAND = 0x0111;

        [DllImport("user32.dll", EntryPoint = "GetParent")]
        public static extern IntPtr GetParent(IntPtr hWnd);

        [DllImport("user32.dll", EntryPoint = "GetCursorPos")]
        public static extern bool GetCursorPos(out Point pt);

        [DllImport("user32.dll", EntryPoint = "WindowFromPoint", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr WindowFromPoint(Point pt);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowText(IntPtr hWnd, [Out, MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowRect(IntPtr hwnd, ref Rectangle rc);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int GetClientRect(IntPtr hwnd, ref Rectangle rc);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int MoveWindow(IntPtr hwnd, int x, int y, int nWidth, int nHeight, bool bRepaint);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
        public static extern int ScreenToClient(IntPtr hWnd, ref Rectangle rect);
        #endregion

        #region 封装API方法
        /// <summary>
        /// 找到句柄
        /// </summary>
        /// <param name="IpClassName">类名</param>
        /// <returns></returns>
        public static IntPtr GetHandle(string IpClassName)
        {
            return FindWindow(IpClassName, null);
        }

        /// <summary>
        /// 找到句柄
        /// </summary>
        /// <param name="p">坐标</param>
        /// <returns></returns>
        public static IntPtr GetHandle(Point p)
        {
            return WindowFromPoint(p);
        }

        //鼠标位置的坐标
        public static Point GetCursorPosPoint()
        {
            Point p = new Point();
            if (GetCursorPos(out p))
            {
                return p;
            }
            return default(Point);
        }

        /// <summary>
        /// 子窗口句柄
        /// </summary>
        /// <param name="hwndParent">父窗口句柄</param>
        /// <param name="hwndChildAfter">前一个同目录级同名窗口句柄</param>
        /// <param name="lpszClass">类名</param>
        /// <returns></returns>
        public static IntPtr GetChildHandle(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass)
        {
            return FindWindowEx(hwndParent, hwndChildAfter, lpszClass, null);
        }

        /// <summary>
        /// 全部子窗口句柄
        /// </summary>
        /// <param name="hwndParent">父窗口句柄</param>
        /// <param name="className">类名</param>
        /// <returns></returns>
        public static List<IntPtr> GetChildHandles(IntPtr hwndParent, string className)
        {
            List<IntPtr> resultList = new List<IntPtr>();
            for (IntPtr hwndClient = GetChildHandle(hwndParent, IntPtr.Zero, className); hwndClient != IntPtr.Zero; hwndClient = GetChildHandle(hwndParent, hwndClient, className))
            {
                resultList.Add(hwndClient);
            }

            return resultList;
        }

        /// <summary>
        /// 给窗口发送内容
        /// </summary>
        /// <param name="hWnd">句柄</param>
        /// <param name="lParam">要发送的内容</param>
        public static void SetText(IntPtr hWnd, string lParam)
        {
            SendMessage(hWnd, WM_SETTEXT, IntPtr.Zero, lParam);
        }
        private const int WM_SETTEXT = 0x000C;

        /// <summary>
        /// 获得窗口内容或标题
        /// </summary>
        /// <param name="hWnd">句柄</param>
        /// <returns></returns>
        public static string GetText(IntPtr hWnd)
        {
            StringBuilder result = new StringBuilder(128);
            GetWindowText(hWnd, result, result.Capacity);
            return result.ToString();
        }

        /// <summary>
        /// 找类名
        /// </summary>
        /// <param name="hWnd">句柄</param>
        /// <returns></returns>
        public static string GetClassName(IntPtr hWnd)
        {
            StringBuilder lpClassName = new StringBuilder(128);
            if (GetClassName(hWnd, lpClassName, lpClassName.Capacity) == 0)
            {
                throw new Exception("not found IntPtr!");
            }
            return lpClassName.ToString();
        }

        /// <summary>
        /// 窗口在屏幕位置
        /// </summary>
        /// <param name="hWnd">句柄</param>
        /// <returns></returns>
        public static Rectangle GetWindowRect(IntPtr hWnd)
        {
            Rectangle result = default(Rectangle);
            GetWindowRect(hWnd, ref result);
            return result;
        }

        /// <summary>
        /// 窗口相对屏幕位置转换成父窗口位置
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="rect"></param>
        /// <returns></returns>
        public static Rectangle ScreenToClient(IntPtr hWnd, Rectangle rect)
        {
            Rectangle result = rect;
            ScreenToClient(hWnd, ref result);
            return result;
        }

        /// <summary>
        /// 窗口大小
        /// </summary>
        /// <param name="hWnd"></param>
        /// <returns></returns>
        public static Rectangle GetClientRect(IntPtr hWnd)
        {
            Rectangle result = default(Rectangle);
            GetClientRect(hWnd, ref result);
            return result;
        }

        public static void GetInfo(IntPtr vHandle)
        {
            SendMessage(vHandle, WM_COMMAND, IDM_VIEWSOURCE, (int)vHandle);

        }

        #endregion

    }
}

 Win32ApiWrapper.cs 文件如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace AutoDownloadGf
{
    public class Win32ApiWrapper
    {
        public const int WM_KEYDOWN = 0x100;
        public const int WM_KEYUP = 0x101;
        public const int VK_CONTROL = 0x11;
        public const int VK_F5 = 0x74;
        public const int KEYEVENTF_KEYUP = 0x2;
        public const int VK_MENU = 0x12;
        public const int WM_SETTEXT = 0xC;
        public const int WM_CLEAR = 0x303;
        public const int BN_CLICKED = 0;
        public const int WM_LBUTTONDOWN = 0x201;
        public const int WM_LBUTTONUP = 0x202;
        public const int WM_CLOSE = 0x10;
        public const int WM_COMMAND = 0x111;
        public const int WM_SYSKEYDOWN = 0x104;
        public const int GW_HWNDNEXT = 2;
        public const int WM_CLICK = 0x00F5;

        private static Dictionary<string, byte> keycode = new Dictionary<string, byte>();

        private delegate bool WNDENUMPROC(IntPtr hWnd, int lParam);

        static Win32ApiWrapper()
        {
            keycode.Add("A", 65);
            keycode.Add("B", 66);
            keycode.Add("C", 67);
            keycode.Add("D", 68);
            keycode.Add("E", 69);
            keycode.Add("F", 70);
            keycode.Add("G", 71);
            keycode.Add("H", 72);
            keycode.Add("I", 73);
            keycode.Add("J", 74);
            keycode.Add("K", 75);
            keycode.Add("L", 76);
            keycode.Add("M", 77);
            keycode.Add("N", 78);
            keycode.Add("O", 79);
            keycode.Add("P", 80);
            keycode.Add("Q", 81);
            keycode.Add("R", 82);
            keycode.Add("S", 83);
            keycode.Add("T", 84);
            keycode.Add("U", 85);
            keycode.Add("V", 86);
            keycode.Add("W", 87);
            keycode.Add("X", 88);
            keycode.Add("Y", 89);
            keycode.Add("Z", 90);
            keycode.Add("0", 48);
            keycode.Add("1", 49);
            keycode.Add("2", 50);
            keycode.Add("3", 51);
            keycode.Add("4", 52);
            keycode.Add("5", 53);
            keycode.Add("6", 54);
            keycode.Add("7", 55);
            keycode.Add("8", 56);
            keycode.Add("9", 57);
            keycode.Add(".", 0x6E);
            keycode.Add("LEFT", 0x25);
            keycode.Add("UP", 0x26);
            keycode.Add("RIGHT", 0x27);
            keycode.Add("DOWN", 0x28);
            keycode.Add("-", 0x6D);
        }

        [DllImport("Gdi32.dll")]
        public extern static int BitBlt(IntPtr hDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop);

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        public extern static IntPtr GetWindow(IntPtr hWnd, int wCmd);

        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, string lParam);

        [DllImport("user32.dll ")]
        public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr childe, string strclass, string FrmText);

        [DllImport("user32.DLL")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        internal static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll")]
        private static extern int GetWindowTextW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll")]
        private static extern bool EnumWindows(WNDENUMPROC lpEnumFunc, int lParam);

        [DllImport("user32.dll")]
        private static extern int GetClassNameW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll")]
        private static extern bool EnumChildWindows(IntPtr hWndParent, WNDENUMPROC lpEnumFunc, int lParam);

        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendTxtMessage(int hWnd,
            // handle to destination window               
            int Msg, // message               
            int wParam, // first message parameter               
            char[] lParam             // int  lParam // second message parameter           
            );

        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(
            int hWnd, // handle to destination window               
            int Msg, // message               
            int wParam, // first message parameter                
            int lParam // second message parameter         
            );

        [DllImport("user32.dll")]
        public static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, int dwExtraInfo);


        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static public extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int Width, int Height, uint flags);

        [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
        public static extern bool SetWindowPos(IntPtr hWnd, int HWND_TOPMOST, int x, int y, int Width, int Height, uint flags);


        [DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "PostMessage")]
        public static extern IntPtr PostMessage(IntPtr hwndParent, int hwndChildAfter, IntPtr wParam, string lpszWindow);
        
        [DllImport("user32.dll ", CharSet = CharSet.Unicode)]
        public static extern IntPtr PostMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); 


        /// <summary>
        /// 获取桌面所有的窗口
        /// </summary>
        /// <returns></returns>
        public static WindowInfo[] GetAllDesktopWindows()
        {
            List<WindowInfo> wndList = new List<WindowInfo>();
            EnumWindows(delegate(IntPtr hWnd, int lParam)
            {
                WindowInfo wnd = new WindowInfo();
                StringBuilder sb = new StringBuilder(256);
                wnd.hWnd = hWnd;
                GetWindowTextW(hWnd, sb, sb.Capacity);
                wnd.SzWindowName = sb.ToString();
                GetClassNameW(hWnd, sb, sb.Capacity);
                wnd.SzClassName = sb.ToString();
                wndList.Add(wnd);
                return true;
            }, 0);

            return wndList.ToArray();
        }


        public static List<WindowInfo> GetWindowByParentHwndAndClassName(IntPtr parentHwnd, string className)
        {
            List<WindowInfo> wndList = new List<WindowInfo>();
            EnumChildWindows(parentHwnd, delegate(IntPtr hWnd, int lParam)
            {
                WindowInfo wnd = new WindowInfo();
                StringBuilder sb = new StringBuilder(256);
                wnd.hWnd = hWnd;
                GetWindowTextW(hWnd, sb, sb.Capacity);
                wnd.SzWindowName = sb.ToString();
                GetClassNameW(hWnd, sb, sb.Capacity);
                wnd.SzClassName = sb.ToString();
                wndList.Add(wnd);
                return true;
            }, 0);
            return wndList.Where(o => o.SzClassName == className).ToList();
        }



        public static List<WindowInfo> GetChildWindowsByParentHwnd(IntPtr parentHwnd)
        {
            List<WindowInfo> childWndList = new List<WindowInfo>();
            EnumChildWindows(parentHwnd, delegate(IntPtr hWnd, int lParam)
            {
                WindowInfo wnd = new WindowInfo();
                StringBuilder sb = new StringBuilder(256);
                wnd.hWnd = hWnd;
                GetWindowTextW(hWnd, sb, sb.Capacity);
                wnd.SzWindowName = sb.ToString();
                GetClassNameW(hWnd, sb, sb.Capacity);
                wnd.SzClassName = sb.ToString();
                childWndList.Add(wnd);
                return true;
            }, 0);

            return childWndList;
        }



    }



    public class WindowInfo
    {
        public IntPtr hWnd { get; set; }

        public string SzWindowName { get; set; }

        public string SzClassName { get; set; }
    }
}

 14.让控件聚焦

this.webBrowser1.Select();
this.webBrowser1.Focus();
userNameElement.Focus();

15.导航指定页面

webBrowser1.Navigate(  @"d:\Test.html");//导航本地网页
webBrowser1.Navigate("http://www.baidu.com");//导航一个网址

16.获取表单元素

//根据Name获取元素
public HtmlElement GetElementByName(WebBrowser wb,string Name)
{
    HtmlElement e = wb.Document.All[Name];
    return e;
}

//根据Id获取元素
public HtmlElement GetElementById(WebBrowser wb, string id)
{
    HtmlElement e = wb.Document.GetElementById(id);
    return e;
}

//根据Index获取元素
public HtmlElement GetElementByIndex(WebBrowser wb,int index)
{
    HtmlElement e = wb.Document.All[index];
    return e;
}

//获取form表单名name,返回表单
public HtmlElement GetElementByForm(WebBrowser wb,string form_name)
{
    HtmlElement e = wb.Document.Forms[form_name];
    return e;
}


//设置元素value属性的值
public void WriteValue(HtmlElement e,string value)
{
    e.SetAttribute("value", value);
}

//执行表单的提交
public void Btn_click(HtmlElement e,string s)
{

    e.InvokeMember(s);
}

 

posted on 2016-04-12 13:29  LinuxPanda  阅读(1993)  评论(0编辑  收藏  举报

导航