Python wheel mouse with win32con

604 Views Asked by At

Please tell me how to solve my little problem.

I am writing automation for the android emulator, where I use the win32api libraries to emulate actions in an inactive program window.

And at some point I need to send the mouse scroll to the emulator. For this I use:

lParam = win32api.MAKELONG (500, 500)

win32api.PostMessage (hwnd, win32con.WM_MOUSEWHEEL, win32con.MK_LBUTTON, lParam)

Thus, I scroll down. But, no matter how long I googling and looking for information, I cannot figure out how I can scroll up in the same way.

Hmm, for thoughts to click I use:

def Click (x, y):

lParam = win32api.MAKELONG (x, y)
win32api.PostMessage (hwnd, win32con.WM_MOUSEMOVE, lParam)
win32api.PostMessage (hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
win32api.PostMessage (hwnd, win32con.WM_LBUTTONUP, win32con.MKF_LEFTBUTTONSEL, lParam)

Otherwise, I could not make a click.

2

There are 2 best solutions below

0
On
import win32gui, win32api, win32con
from time import sleep

def wheel(hWnd,x,y,delta):
    lParam = win32api.MAKELONG (x, y)
    wParam = win32api.MAKELONG(0, delta)
    #hWnd= win32gui.FindWindowEx(hWnd, None, None, None)
    #win32gui.SendMessage(hWnd, win32con.WM_MOUSEMOVE, win32con.MK_LBUTTON, lParam)
    win32api.PostMessage(hWnd, win32con.WM_MOUSEWHEEL, wParam, lParam)
    #win32api.PostMessage(hWnd, win32con.WM_MOUSEWHEEL, 120, lParam)
    
def hWndByInTitleSubSrting(subString):# get window handler
    _hwnd = []
    def enumHandler(hwnd, lParam):
        if win32gui.IsWindowVisible(hwnd):
            if subString in win32gui.GetWindowText(hwnd):
                _hwnd.append(hwnd)
    win32gui.EnumWindows(enumHandler, None)
    return _hwnd

hwnds = hWndByInTitleSubSrting('Microsoft​ Edge')
hwnd = hwnds[0] # get first Microsoft​ Edge window 

x,y=50,50+170 # 170 window title height in my Microsoft​ Edge
delta = 120

count = 10
for i in range(count): # +delta
    wheel(hwnd,x,y,delta*5)
    sleep(0.2)
    
for i in range(count): # -delta
    wheel(hwnd,x,y,delta*-5)

delta is 120*n where n is an integer (..., -2, -1, 0, 1, 2, ...). use -delta and +delta for scroll direction. this code is refactored based on the code in this question Different behaviours encountered when posting a mouse scroll message to different windows with win32gui.

1
On

I solved this problem this way:

win32api.PostMessage(hwnd, win32con.WM_MOUSEWHEEL, win32con.WHEEL_DELTA * 5, lParam)