如何在带有win32api的窗口上实现后台鼠标拖动

2024-04-29 22:14:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究移植一些我使用pyautogui编写的自动化代码,它将鼠标从起始位置拖到结束位置,我想使用win32api通过SendMessage功能实现这些相同的功能。我已经成功地移植了click事件,但是在拖放实现上遇到了问题。你知道吗

这是我用Python写的一个游戏机器人。我可以访问windows hwnd,以及映射到所需的正确位置的坐标。目前,我的实现实际上没有在屏幕上拖动或执行任何操作。你知道吗

evt_d = self.SUPPORTED_CLICK_EVENTS[button][0]  # win32con.WM_LBUTTONDOWN
evt_u = self.SUPPORTED_CLICK_EVENTS[button][1]  # win32con.WM_LBUTTONUP

start_param = win32api.MAKELONG(start[0], start[1])  # Starting location.
end_param = win32api.MAKELONG(end[0], end[1])  # Ending location.

# Moving the mouse to the starting position for the mouse drag.
# Mouse left button is DOWN after this point.
win32api.SendMessage(hwnd, evt_d, 1, start_param)

# Attempting to copy some of the implementation from pywinauto,
# to no avail...
for i in range(5):
    win32api.SendMessage(hwnd, win32con.WM_MOUSEMOVE, 1, win32api.MAKELONG(start[0] + i, start[1]))
            time.sleep(0.1)

win32api.SendMessage(hwnd, win32con.WM_MOUSEMOVE, 1, end_param)
time.sleep(0.1)
win32api.SendMessage(hwnd, evt_u, 0, end_param)

我希望鼠标在屏幕上拖动,导致当前在窗口中打开的面板根据提供的坐标向上或向下移动。你知道吗

更新:

所以,我对此做了更多的调查,我所看到的pywinauto的实现似乎并不真正适合我的需要,这是有道理的。你知道吗

根据拖动的方向(x轴、y轴),您希望消息循环从坐标中进行加减操作,并且必须在发送的每个api消息之间添加一个简短的time.sleep调用。你知道吗

下面是一个粗略的实现。你知道吗

# Determine amount of mouse movements needed.
# Only supports Y axis dragging, X axis requires more conditionals.
if start[1] > end[1]:
    down = True
    clicks = start[1] - end[1]
else:
    down = False
    clicks = end[1] - start[1]

for i in range(clicks):
    param = win32api.MAKELONG(start[0], start[1] - i if down else start[1] + i)
    win32api.SendMessage(hwnd, win32con.WM_MOUSEMOVE, 1, param)
    time.sleep(0.05)  # A sleep is required here, or the message does nothing.

win32api.SendMessage(hwnd, win32con.WM_MOUSEMOVE, 1, end_param)
time.sleep(0.1)
win32api.SendMessage(hwnd, win32con.WM_LBUTTONUP, 0, end_param)

这是可行的,但可以在许多方面加以改进。。。我在网上找不到任何关于用Python做这件事的很好的参考资料,如果有人对如何更优雅地做这件事有一些额外的意见或想法,我会很高兴得到反馈的!你知道吗


Tags: thetimeparambuttonsleepstartendevt