【问题标题】:SendInput moves the cursor when I try to perform a mouse click当我尝试执行鼠标单击时,SendInput 移动光标
【发布时间】:2015-03-21 19:05:04
【问题描述】:

我正在尝试使用 SendInput 模拟鼠标左键单击,它可以工作,但也会将光标移动到屏幕的左上角 (0,0),我不知道为什么。

(我使用相同的结构来移动光标(相对和绝对),这是有效的。)

private static void Send(INPUT input)
{
  SendInput(1, ref input, Marshal.SizeOf(new INPUT()));
}
private static void MouseAction(MouseFlags mf)
{
  INPUT aInput = new INPUT();
  aInput.type = InputType.INPUT_MOUSE;
  aInput.mkhi.mi.dwFlags = mf;

  Send(aInput);
}

// Performs a LeftClick but moves the cursor to (0.0)
public static void LeftClick()
{
  MouseAction(MouseFlags.MOUSEEVENTF_LEFTDOWN | MouseFlags.MOUSEEVENTF_LEFTUP);
}

当我填写所有结构成员时,结果是一样的。 完整的 INPUT 定义:

[StructLayout(LayoutKind.Sequential)]
struct INPUT
{
    public InputType type;
    public MouseKeyboardHardwareUnion mkhi;
}
[StructLayout(LayoutKind.Explicit)]
struct MouseKeyboardHardwareUnion
{
    [FieldOffset(0)]
    public MOUSEINPUT mi;

    [FieldOffset(0)]
    public KEYBDINPUT ki;
}
[StructLayout(LayoutKind.Sequential)]
struct MOUSEINPUT
{
    public int dx;
    public int dy;
    public uint mouseData;
    public MouseFlags dwFlags;
    public uint time;
    public IntPtr dwExtraInfo;
}
// Not relevant
[StructLayout(LayoutKind.Sequential)]
struct KEYBDINPUT
{
    public KeyboardVirtual wVk;
    public ushort wScan;
    public KeyboardFlags dwFlags;
    public uint time;
    public IntPtr dwExtraInfo;
}

用光标的当前位置填充 MOUSEINPUT 的 dx 和 dy 字段似乎也不能解决问题。

【问题讨论】:

    标签: c# windows winapi sendinput


    【解决方案1】:

    首先,如果您能显示 INPUT 结构的定义,这将非常有帮助。

    其次,如果您的 INPUT 结构包含 X 和 Y 坐标,请使用:

    aInput.somethingX = Cursor.Position.X;
    aInput.somethingY = Cursor.Position.Y;
    

    因为否则它当然会重置您的光标位置。

    第三,只需在 google 和 stackoverflow 上搜索,您就会发现很多人已经问过这个问题并得到了有用的答案,例如 this

    【讨论】:

    • 我按照您的要求编辑了我的问题,并尝试了您的建议,但光标仍转到 (0.0)
    【解决方案2】:

    我想通了,问题不在于 INPUT 结构,我在 EventArgs 构造函数中调用了 LeftClick() 函数。在我把它移到外面之后,它工作得很好。

    【讨论】:

      猜你喜欢
      • 2011-12-22
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多