SendInput 始终将鼠标指针移动到左上角

SendInput always moves mouse pointer to left top corner

我想使用下面的代码以编程方式将鼠标运动合成到屏幕上的一个点 (100,100),但它移动到左上角。有什么问题吗?

#include "stdafx.h"
#include<Windows.h>

int main() {
  INPUT input;
  input.type = INPUT_MOUSE;
  input.mi.dx = 100;
  input.mi.dy = 100;
  input.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
  input.mi.mouseData = 0;
  input.mi.dwExtraInfo = NULL;
  input.mi.time = 0;
  SendInput(1, &input, sizeof(INPUT));
  return 0;
}

PS。我在 Windows 10x64 上用 VS2017 编译了它。我也有 运行 Win7 的代码

PPS。当我删除 MOUSEEVENTF_ABSOLUTE 标志时,它会移动到相对位置。

API 调用遵循 documented 行为:

MOUSEEVENTF_ABSOLUTE: The dx and dy members contain normalized absolute coordinates. [...] see the following Remarks section.

备注部分确实描述了归一化坐标:

If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain normalized absolute coordinates between 0 and 65,535. The event procedure maps these coordinates onto the display surface. Coordinate (0,0) maps onto the upper-left corner of the display surface; coordinate (65535,65535) maps onto the lower-right corner. In a multimonitor system, the coordinates map to the primary monitor.

要将鼠标移动到绝对位置,首先需要查询显示表面大小(例如通过调用GetMonitorInfor),并适当缩放坐标。

给定以设备单位为单位的点和显示表面尺寸作为输入,以下函数对点进行归一化:

POINT normalize(POINT const& pt_in_px, RECT const& display_size_in_px)
{
    POINT pt_normalized{};

    auto const width_in_px{ display_size_in_px.right - display_size_in_px.left };
    auto const height_in_px{ display_size_in_px.bottom - display_size_in_px.top };

    pt_normalized.x = ::MulDiv(pt_in_px.x, 65536, width_in_px);
    pt_normalized.y = ::MulDiv(pt_in_px.y, 65536, height_in_px);

    return pt_normalized;
}