远程控制之鼠标、按键模拟
做远程控制相关软件(远程办公、远程教育、远程协助等)时,鼠标、按键模拟必不可少。在windows环境下,windows API提供的两个方法可以很方便的完成鼠标、按键的模拟:mouse_event、keybd_event。模拟鼠标按键单击时,首先要计算鼠标位置X、Y(使用ClientToScreen),并把被控端鼠标位置移到X、Y位置,即鼠标Move事件(SetCursorPos),之后使用mouse_event来模拟需要执行的鼠标行为,主要为按下、弹起。按键的模拟主要是键的按下与弹起。
鼠标模拟:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // MOUSEEVENTF_LEFTDOWN = $0002; //左键按下 2 // MOUSEEVENTF_LEFTUP = $0004; //左键弹起 3 // MOUSEEVENTF_RIGHTDOWN = $0008; //右键按下 4 // MOUSEEVENTF_RIGHTUP = $0010; //右键弹起 5 // MOUSEEVENTF_MIDDLEDOWN = $0020; //中键按下 6 // MOUSEEVENTF_MIDDLEUP = $0040; //中键弹起 7 8 //设置鼠标位置(模拟鼠标必须先设置正确位置) 9 SetCursorPos(X, Y) 10 11 //左键单击(右键、中键与此类似) 12 mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0) 13 mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0) 14 //左键单击组合写法 15 mouse_event(MOUSEEVENTF_LEFTDOWN or MOUSEEVENTF_LEFTUP, x, y, 0, 0) 16 17 //左键双击(右键、中键与此类似) 18 mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0) 19 mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0) 20 mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0) 21 mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0) 22 //左键双击组合写法 23 mouse_event(MOUSEEVENTF_LEFTDOWN or MOUSEEVENTF_LEFTUP, x, y, 0, 0) 24 mouse_event(MOUSEEVENTF_LEFTDOWN or MOUSEEVENTF_LEFTUP, x, y, 0, 0)
键盘模拟:
1 //按下A键Ord('A')为取按键的ASCII值 2 keybd_event(Ord('A'), 0, 0, 0); 3 //放开A键(键盘的一次敲击就执行了相应键的一次按下与放开) 4 keybd_event(Ord('A'), 0, KEYEVENTF_KEYUP, 0); 5 6 //组合键:Ctrl + A 7 keybd_event(VK_CONTROL, 0, 0, 0); 8 keybd_event(Ord('A'), 0, 0, 0); 9 keybd_event(Ord('A'), 0, KEYEVENTF_KEYUP, 0); 10 keybd_event(VK_CONTROL, 0, KEYEVENTF_KEYUP, 0);