CGEventPost 不总是移动鼠标 macOS

CGEventPost does not always move the mouse macOS

我在 Python 环境中使用 Quartz Event Services 在 macOS Sierra 中尝试以编程方式移动鼠标时遇到问题。

例如:

当我运行这个脚本时:

from Quartz.CoreGraphics import CGEventCreateMouseEvent
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGMouseButtonLeft
from Quartz.CoreGraphics import kCGEventMouseMoved
from Quartz.CoreGraphics import kCGHIDEventTap


def MouseMove(x, y):
        event = CGEventCreateMouseEvent(None, kCGEventMouseMoved, (x, y), kCGMouseButtonLeft)
        CGEventPost(kCGHIDEventTap, event)

MouseMove(100, 100)

一切正常,鼠标移动到 (x: 100, y: 100)

但是,出于某种原因,此过程无法在某些应用程序中移动鼠标。特别是在我的情况下,我的 MacBook 是 运行ning Call of Duty: Modern Warfare 2 on Steam 并且以这种方式移动鼠标不会在此应用程序中注册,但有趣的是我仍然能够使用 [=12= 在应用程序中生成鼠标点击] 只是没有鼠标移动。

所以我做了一些研究,试图找出发生这种情况的原因,我在网上找到的与我的问题最接近的东西是 this question on SO and the reason I mention this is because I'm wondering if like in the linked question I need to call a method similar to something like CGEventSetIntegerValueField only instead of updating the kCGMouseEventClickState update a mouse event pertaining to the movement of the mouse so that the application will know that the mouse has indeed moved. However I have not found such a method in the CGEventField documentation,我只是觉得我遗漏了什么或也许这甚至不涉及问题,但这是我能找到的唯一线索。

请帮忙。我将不胜感激任何人可能提出的任何建议。

我找到了答案。

我更改了这一行:

event = CGEventCreateMouseEvent(None, type, (x, y), kCGMouseButtonLeft)
CGEventPost(kCGHIDEventTap, event)

为此:

CGPostMouseEvent((x, y), True, 0, False)

当然还有导入:CGPostMouseEvent

因此,移动鼠标在任何地方和所有应用程序中都有效。它起作用的原因是因为 CGPostMouseEvent 发生在比 CGEventPost 更深的本地机器上。