我想用下面的代码以编程方式将鼠标运动合成到屏幕上的一个点 (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;
}
附言。我已经在 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;
}
关于c++ - SendInput 始终将鼠标指针移动到左上角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49026921/