【发布时间】:2020-07-06 15:15:40
【问题描述】:
我想以编程方式将鼠标输入发送到我连接的任何显示器。
我知道我可以使用 SendInput 函数来执行此操作,但我目前的方法不适用于多显示器设置。
我正在使用以下方法:
- 获取点击点相对于当前屏幕的像素坐标;
- 使用 GetMonitorInfoW 函数和适当的 HMONITOR 句柄获取当前屏幕左上角像素的像素坐标;
- 获取相对于整个虚拟屏幕的像素坐标:为此,我们将当前屏幕边缘的坐标(左上角像素)与点击点的坐标相加;
- 将生成的像素坐标转换为绝对坐标 (0-65535),供 SendInput 函数使用;
- 将SendInput 函数与MOUSEEVENTF_ABSOLUTE 一起使用| MOUSEEVENTF_VIRTUALDESK 标志和相对于整个虚拟桌面的绝对坐标。
但是,在我当前的代码中,鼠标输入的位置错误。 我对如何正确计算绝对坐标感到困惑。
目前,我确实使用another question 上讨论的公式检索绝对坐标。 要获取虚拟屏幕的宽度/高度,我使用GetSystemMetrics 和 SM_CXVIRTUALSCREEN/SM_CYVIRTUALSCREEN 参数。
// ________________________________________________
//
// GetAbsoluteCoordinate
//
// PURPOSE:
// Convert pixel coordinate to absolute coordinate (0-65535).
//
// RETURN VALUE:
// Absolute Coordinate
// ________________________________________________
//
UINT16 GetAbsoluteCoordinate(INT PixelCoordinate, INT ScreenResolution)
{
UINT16 AbsoluteCoordinate = ( (65536 * PixelCoordinate) / ScreenResolution ) + 1;
return AbsoluteCoordinate;
}
// ________________________________________________
//
// GetAbsoluteCoordinates
//
// PURPOSE:
// Retrieve virtual screen absolute coordinates from pixel coordinates.
//
// PARAMETERS:
// x, y coordinates passed by reference. These will be changed by the function and used as return values.
//
// RETURN VALUE:
// None (see parameters)
// ________________________________________________
//
void GetAbsoluteCoordinates(INT32 &X, INT32 &Y)
{
// Get multi-screen coordinates
MONITORINFO MonitorInfo = { 0 };
MonitorInfo.cbSize = sizeof(MonitorInfo);
if (GetMonitorInfoW(hMonitor, &MonitorInfo))
{
// 1) Get pixel coordinates of topleft pixel of target screen, relative to the virtual desktop ( coordinates should be 0,0 on Main screen);
// 2) Get pixel coordinates of mouse cursor, relative to the target screen;
// 3) Sum topleft margin pixel coordinates with mouse cursor coordinates;
X = MonitorInfo.rcMonitor.left + X;
Y = MonitorInfo.rcMonitor.top + Y;
// 4) Transform the resulting pixel coordinates into absolute coordinates.
X = GetAbsoluteCoordinate(X, GetSystemMetrics(SM_CXVIRTUALSCREEN));
Y = GetAbsoluteCoordinate(Y, GetSystemMetrics(SM_CYVIRTUALSCREEN));
}
}
// ________________________________________________
//
// SendMouseInput
//
// PURPOSE:
// Send mouse input, supporting any of the connected displays
//
// PARAMETERS:
// X, Y are pixel coordinates, relative to the current screen.
// ________________________________________________
//
void SendMouseInput(INT X, INT Y)
{
INPUT Input;
GetAbsoluteCoordinates(X, Y);
memset(&Input, 0, sizeof(INPUT));
Input.type = INPUT_MOUSE;
Input.mi.dx = X;
Input.mi.dy = Y;
Input.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK | MOUSEEVENTF_MOVE | MOUSEEVENTF_LEFTDOWN;
SendInput(1, &Input, sizeof(Input));
}
【问题讨论】:
标签: c++ c windows winapi sendinput