C# 模拟鼠标、键盘事件、获取控件相对屏幕位置

假设winform有一个按钮和一个控件secondPic_1,现需求如下:

点击按钮实现鼠标自动移动到secondPic_1中央部位,点击鼠标左键,并模拟键盘输入‘M’。

#region 鼠标、键盘点击
        [DllImport("user32.dll", EntryPoint = "keybd_event", SetLastError = true)]
        public static extern void keybd_event(Keys bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
        const int KEYEVENTF_KEYUP = 0x0002;

        //模拟鼠标点击
        [System.Runtime.InteropServices.DllImport("user32")]
        private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
        //模拟键盘点击
        [DllImport("user32.dll", EntryPoint = "PostMessageA", SetLastError = true)]
        public static extern int PostMessage(IntPtr hWnd, int Msg, Keys wParam, int lParam);

        //移动鼠标 
        const int MOUSEEVENTF_MOVE = 0x0001;
        //模拟鼠标左键按下 
        const int MOUSEEVENTF_LEFTDOWN = 0x0002;
        //模拟鼠标左键抬起 
        const int MOUSEEVENTF_LEFTUP = 0x0004;
        //标示是否采用绝对坐标 
        const int MOUSEEVENTF_ABSOLUTE = 0x8000;
        //模拟鼠标右键按下 
        const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
        //模拟鼠标右键抬起 
        const int MOUSEEVENTF_RIGHTUP = 0x0010;
        #endregion

        /// 
        /// 获取控件相对于屏幕左上角的位置
        /// 
        /// 
        /// 
        private Point LocationOnClient(Control c)
        {
            Point retval = new Point(0, 0);
            do
            {
                retval.Offset(c.Location);
                c = c.Parent;
            }
            while (c != null);
            return retval;
        }
       
        /// 
        /// 点击按钮,鼠标自动移动到某个控件,左击控件并键入键盘M键
        /// 
        /// 
        /// 
        private void pictureBox20_Click(object sender, EventArgs e)
        {
            //获取电脑分辨率
            int sceenHeight = Screen.PrimaryScreen.Bounds.Height;
            int screenWeight = Screen.PrimaryScreen.Bounds.Width;

            //获取控件的位置
            Point screen = LocationOnClient(secondPic_1);
            Point screenP = new Point(screen.X + secondPic_1.Size.Width / 2, screen.Y + secondPic_1.Size.Height / 2);
            Console.WriteLine("相对屏幕:" + screenP.X + "  " + screenP.Y);

            //将鼠标移动到控件的位置上,模拟鼠标左击
            mouse_event(MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, screenP.X * 65536 / screenWeight, screenP.Y * 65536 / sceenHeight, 0, 0);
           
            //模拟键盘输入
            keybd_event(Keys.M, 0, 0, 0);
        }

 

你可能感兴趣的:(asp.net)