在C#中如何模拟鼠标键盘操作
2009-01-12 16:59 yufun 阅读(1361) 评论(0) 编辑 收藏 举报上一篇讲了在自动化测试中如果控件不能识别,我们最后的办法是模拟鼠标键盘,这一篇就讲如何来做。
首先我先讲在C#中怎么做,至于在C++或者脚本中怎么做,留在后边来讲
对C#来说,键盘的模拟比较简单,在.Net Framework中System.Windows.Forms.SendKeys这个类
鼠标呢,看下边代码:
1: [DllImport("user32")]
2: public static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
3:
4: [Flags]
5: public enum MouseEventFlags
6: {
7: Move = 0x0001,
8: LeftDown = 0x0002,
9: LeftUp = 0x0004,
10: RightDown = 0x0008,
11: RightUp = 0x0010,
12: MiddleDown = 0x0020,
13: MiddleUp = 0x0040,
14: Wheel = 0x0800,
15: Absolute = 0x8000
16: }
17:
18: void PixelsToAbsCoors(double x, double y, ref double xOut, ref double yOut)
19: {
20: //points are based on current screen size setting
21: xOut = x * 65536 / Screen.PrimaryScreen.Bounds.Width + 0.5;
22: yOut = y * 65536 / Screen.PrimaryScreen.Bounds.Height + 0.5;
23: }
24: public void Move(double x, double y)
25: {
26: PixelsToAbsCoors(x, y, ref x, ref y);
27: mouse_event((int)(MouseEventFlags.Move | MouseEventFlags.Absolute), (int)x, (int)y, 0, 0);
28: }
29: public void Click(double x, double y)
30: {
31: Move(x, y);
32: PixelsToAbsCoors(x, y, ref x, ref y);
33: mouse_event((int)(MouseEventFlags.LeftDown | MouseEventFlags.Absolute), (int)x, (int)y, 0, 0);
34: mouse_event((int)(MouseEventFlags.LeftUp | MouseEventFlags.Absolute), (int)x, (int)y, 0, 0);
35: }