Automate Everything

关于自动化相关的任何东西,包括自动化测试,Visual Studio宏, 自动化安装部署等
星期五, 2008-04-11, 18:54

在C#中如何模式鼠标键盘操作

上一篇讲了在自动化测试中如果控件不能识别,我们最后的办法是模拟鼠标键盘,这一篇就讲如何来做。

首先我先讲在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 = 0×0001,
   8:     LeftDown = 0×0002,
   9:     LeftUp = 0×0004,
  10:     RightDown = 0×0008,
  11:     RightUp = 0×0010,
  12:     MiddleDown = 0×0020,
  13:     MiddleUp = 0×0040,
  14:     Wheel = 0×0800,
  15:     Absolute = 0×8000
  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: }
把这篇文章分享到: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • bodytext
  • Google
  • Facebook
  • Furl
太差了有点差马马虎虎了很不错非常好 (2 votes, average: 5 out of 5)
Loading ... Loading ...

随机文章

  • 55招玩转Google
  • 你是否知道-VisualStudio中怎么使用工程模板
  • Triivi:“搜狗式”英文输入法
  • .Net 内存泄露检查以及垃圾回收机制
  • 在自动化测试中,如果控件不能识别,你会这么做?
  • 兄弟,建站写博客很辛苦的,给点意见吧:)