模拟鼠标移动

时间:2013-08-22 10:38:05

标签: c# .net

我的UserControl中有ListView和图像。当我从图片图片中移除鼠标时,我正在重新绘制图片。 但是,当我第二次在同一张照片上拍摄时,不想再重画,但是当我带走了ListView的教堂并再次使用navozhu时。我以为我可以做一个仿鼠标。或者告诉我更好的事情。

[DllImport("user32.dll")]
static extern bool SetCursorPos(int X, int Y);

它有效,但我看到了一丝鼠标。

1 个答案:

答案 0 :(得分:6)

为了模拟鼠标移动,按钮的点击等,您可以尝试使用mouse_event API函数。请注意,它适用于 mickeys 而非像素

http://msdn.microsoft.com/en-us/library/windows/desktop/ms646260(v=vs.85).aspx

    [DllImport("User32.dll",
               EntryPoint = "mouse_event",
               CallingConvention = CallingConvention.Winapi)]
    internal static extern void Mouse_Event(int dwFlags,
                                            int dx,
                                            int dy,
                                            int dwData,
                                            int dwExtraInfo);

    [DllImport("User32.dll",
               EntryPoint = "GetSystemMetrics",
               CallingConvention = CallingConvention.Winapi)]
    internal static extern int InternalGetSystemMetrics(int value);

   ...

   // Move mouse cursor to an absolute position to_x, to_y and make left button click:
   int to_x = 500;
   int to_y = 300;

   int screenWidth = InternalGetSystemMetrics(0);
   int screenHeight = InternalGetSystemMetrics(1);

   // Mickey X coordinate
   int mic_x = (int) System.Math.Round(to_x * 65536.0 / screenWidth);
   // Mickey Y coordinate
   int mic_y = (int) System.Math.Round(to_y * 65536.0 / screenHeight);

   // 0x0001 | 0x8000: Move + Absolute position
   Mouse_Event(0x0001 | 0x8000, mic_x, mic_y, 0, 0);
   // 0x0002: Left button down
   Mouse_Event(0x0002, mic_x, mic_y, 0, 0);
   // 0x0004: Left button up
   Mouse_Event(0x0004, mic_x, mic_y, 0, 0);