C#マウス、キーボードイベントのシミュレーション、コントロールの画面位置の取得

2663 ワード

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);
        }