【问题标题】:Simulate Mouse Click and Mouse Move in Windows 7 using C#使用 C# 在 Windows 7 中模拟鼠标单击和鼠标移动
【发布时间】:2011-01-10 19:16:37
【问题描述】:

我编写了一段代码来模拟鼠标点击,这在我的 Vista 中运行良好。但是当我在 Windows 7 中测试它时,它不会生成点击事件。有人可以帮忙吗?我在下面添加代码 sn-p。 谢谢, 尼基尔

[DllImport("user32.dll")]
        static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);


[Flags]
        public enum MouseEventFlags
        {
            LEFTDOWN = 0x00000002,
            LEFTUP = 0x00000004,
            MIDDLEDOWN = 0x00000020,
            MIDDLEUP = 0x00000040,
            MOVE = 0x00000001,
            ABSOLUTE = 0x00008000,
            RIGHTDOWN = 0x00000008,
            RIGHTUP = 0x00000010
        }

System.Windows.Forms.Cursor.Hide();
System.Windows.Forms.Cursor.Position = new System.Drawing.Point(xinc + rct.Left, yinc + rct.Top);

int X = System.Windows.Forms.Cursor.Position.X;
int y = System.Windows.Forms.Cursor.Position.Y;

mouse_event((int)(MouseEventFlags.LEFTDOWN), 0, 0, 0, 0);
mouse_event((int)(MouseEventFlags.LEFTUP), 0, 0, 0, 0);


System.Windows.Forms.Cursor.Position = new System.Drawing.Point(0, 0);
System.Windows.Forms.Cursor.Show();

【问题讨论】:

  • mouse_event 已被 SendInput 完全取代。如果更新为 SendInput,您的代码是否有效?
  • @Michael : 嗨,您能否提供一个示例或链接以在 c# 中使用发送输入?

标签: c# .net winforms


【解决方案1】:

我的水晶球说你不只是升级到 Win7,你还得到了 64 位版本。以前您拥有的是 32 位版本的 Vista。您的 mouse_event() 声明是错误的。最后一个参数是 IntPtr,而不是 int。

球表现如何?

【讨论】:

  • 这很奇怪,他使用的完全相同的签名对我来说效果很好:stackoverflow.com/questions/1740045/…
  • @ohadsc - pinvoke.net 链接无处不在,同时使用 IntPtr 和 int。您的声明仅适用于 32 位版本的 Windows Windows Mobile。后者将其记录为 int。没关系,它永远不会有 64 位版本。也许这个功能被弃用是有充分理由的:)
  • 该线程中标记的答案是惊人的错误。无论他们使用什么操作系统,没有人能做到这一点。也许他们通过了很多零。
  • 是的,我已经从 32 位迁移到 64 位。我认为这就是问题所在。您能否告诉如何为 64 位版本重写上述版本。我也检查了你提到的错误,但我在这里找到了两种方法pinvoke.net/default.aspx/user32/mouse_event.html?diff=y你能帮忙吗?
  • 拍球,干得好。正如我所说,将 dwExtraInfo 参数的类型从 int 更改为 IntPtr。在调用中传递 IntPtr.Zero。
【解决方案2】:

不确定这是否会对您有所帮助,但您是否了解过 UI 自动化? link text

【讨论】:

    【解决方案3】:

    对我有用的一个技巧是在mouse_event 调用之前使用具有相同坐标的SetCursorPos。我也刚刚验证了以下工作(在 winforms 上):

        public static void LeftClick(int x, int y)
        {
            Cursor.Position = new System.Drawing.Point(x, y); //<= fails without this
            mouse_event((int)(MouseEventFlags.LEFTDOWN), 0, 0, 0, 0);
            mouse_event((int)(MouseEventFlags.LEFTUP), 0, 0, 0, 0);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 2017-09-30
      • 2011-01-25
      • 1970-01-01
      • 2012-11-14
      • 1970-01-01
      相关资源
      最近更新 更多