windows 如何从代码模拟鼠标事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5164774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:18:45  来源:igfitidea点击:

How can I simulate mouse events from code?

cwindowswinapimousemouseevent

提问by Dharma

I would like to simulate mouse events using the Win32 API; how can I do it?

我想使用 Win32 API 模拟鼠标事件;我该怎么做?

What I want to do is simulate the event at the most basic level, the level at which the system has just the event type and the co-ordinates and hasn't yet figured which window it must relay it to.

我想要做的是在最基本的级别模拟事件,在该级别系统只有事件类型和坐标,但尚未确定必须将其中继到哪个窗口。

I don't know if that's how things work. Either way, I need help doing it. Would I have to meddle at the driver level?!

我不知道事情是不是这样。无论哪种方式,我都需要帮助。我是否必须在驱动程序级别进行干预?!

To make my requirements clear, I don't want to target any window, I just want the system to think the mouse was clicked or moved by the user. And I would be coding in C.

为了明确我的要求,我不想针对任何窗口,我只想让系统认为用户单击或移动了鼠标。我会用 C 编码。

回答by Cody Gray

You're looking for the SendInputfunction, which allows you to synthesize mouse movements and button clicks in your code by specifying an array of INPUTstructurescorresponding to input events.

您正在寻找SendInput函数,它允许您通过指定与输入事件对应的INPUT结构数组来合成代码中的鼠标移动和按钮点击。

UINT WINAPI SendInput(
  __in  UINT nInputs,     // number of structures in the pInputs array
  __in  LPINPUT pInputs,  // an array of INPUT structures, representing an event
  __in  int cbSize        // the size, in bytes, of an INPUT structure
);

Note, however, that this function is subject to User Interface Privilege Isolation (UIPI), which means that your application is only permitted to inject input to applications that are running at an equal or lesser integrity level.

但是请注意,此功能受用户界面特权隔离 (UIPI) 的约束,这意味着您的应用程序只能向以相同或更低完整性级别运行的应用程序注入输入。

回答by Chris

Use mouse_event(winuser.h). The following code will move the mouse then perform a click at the new location. You can do this in two lines but this is more verbose.

使用mouse_event(winuser.h)。以下代码将移动鼠标,然后在新位置单击。你可以用两行来完成,但这更冗长。

Note that X and Y are specified in mickeys, 0 to 65535. This is then mapped onto the current resolution, i.e. 0,0 will be the top left corner and 65535,65535 will be the lower right hand corner.

请注意,X 和 Y 在mickeys中指定,0 到 65535。然后将其映射到当前分辨率,即 0,0 将是左上角,65535,65535 将是右下角。

mouse_event(MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, x, y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);