【问题标题】:How can I simulate mouse events from code?如何从代码中模拟鼠标事件?
【发布时间】:2011-07-07 02:12:35
【问题描述】:

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

我想要做的是在最基本的级别模拟事件,系统只有事件类型和坐标并且还没有计算出必须将其中继到哪个窗口的级别。

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

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

【问题讨论】:

    标签: c windows winapi mouse mouseevent


    【解决方案1】:

    使用mouse_event (winuser.h)。以下代码将移动鼠标然后在新位置执行单击。您可以分两行执行此操作,但这更冗长。

    请注意,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);
    

    【讨论】:

    • 根据MSDN's docs,mouse_event 已被 SendInput 取代。他们建议改用 SendInput。
    • mouse_event 函数似乎不适用于 Windows 10,但 Cody 的 SendInput 方法可以。
    【解决方案2】:

    您正在寻找SendInput function,它可以让您合成鼠标 通过指定与输入事件对应的INPUT structures 数组,在代码中移动和按钮点击。

    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
    );
    

    但是请注意,此函数受User Interface Privilege Isolation (UIPI) 约束,这意味着您的应用程序只被允许向以相同或更低完整性级别运行的应用程序注入输入。

    【讨论】:

    • 感谢您提到 integrity level 为我的应用程序管理员权限解决了这个问题 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2011-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多