当前位置:   article > 正文

C# 使用Win32 API模拟键盘鼠标操作网页

public static extern bool setcursorpos(int x, int y);

在webbrowser控件中的document complete 事件中设置链接到自身

        private void ieFrame_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            foreach (HtmlElement link in ieFrame.Document.Links)
            {
                link.SetAttribute("target", "_self");
            }

            foreach (HtmlElement form in ieFrame.Document.Forms)
            {
                form.SetAttribute("target", "_self");
            }
        }

使用下面封装完的函数模拟操作即可

#region 系统API申明区域
        [DllImport("user32.dll")]
        public static extern bool SetCursorPos(int x, int y);

        [Flags]
        public enum MouseEventFlag : uint
        {
            ABSOLUTE = 0x8000,
            MOVE = 0x0001,
            LEFTDOWN = 0x0002,
            LEFTUP = 0x0004,
            RIGHTDOWN = 0x0008,
            RIGHTUP = 0x0010,
            MIDDLEDOWN = 0x0020,
            MIDDLEUP = 0x0020,
            XDOWN = 0x0080,
            XUP = 0x0100,
            WHEEL = 0x0800,
            HWHEEL = 0x01000,
            VIRTUALDESK = 0x4000
        }

        [DllImport("user32.dll")]
        public static extern bool mouse_event(MouseEventFlag dwFlags, int dx, int dy, uint cButton, UIntPtr dwExtraInfo);

        [DllImport("user32.dll")]
        public static extern void keybd_event(byte bVk, byte bScan, int dwFlags, UIntPtr dwExtraInfo);
        /// <summary>
        /// 模拟按左键
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public void LeftClick(int x, int y)
        {
            Point p = Control.MousePosition;
            SetCursorPos(x, y);
            mouse_event(MouseEventFlag.LEFTDOWN, 0, 0, 0, UIntPtr.Zero);
            mouse_event(MouseEventFlag.LEFTUP, 0, 0, 0, UIntPtr.Zero);
            SetCursorPos(p.X, p.Y);
        }
        /// <summary>
        /// 模拟键盘操作
        /// </summary>
        /// <param name="k"></param>
        public void PressKey(Keys k)
        {
            keybd_event((byte)k, 0, 0, UIntPtr.Zero);
            keybd_event((byte)k, 0, 0x2, UIntPtr.Zero);
        }
        #endregion

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/309776?site
推荐阅读
相关标签
  

闽ICP备14008679号