python win32 simulate click

前端 未结 2 1913
夕颜
夕颜 2020-12-08 17:40

Let\'s say I\'ve got a window for which I want to simulate a mouse click at a specific x, y coordinate. I already have the hwnd but I\'m not sure how to construct the lParam

2条回答
  •  孤街浪徒
    2020-12-08 18:36

    You can use the low level windows api thanks to ctypes. See an example below (adapted from something i didn't test it but it should be ok)

    import ctypes
    MOUSEEVENTF_MOVE = 0x0001 # mouse move
    MOUSEEVENTF_ABSOLUTE = 0x8000 # absolute move
    MOUSEEVENTF_MOVEABS = MOUSEEVENTF_MOVE + MOUSEEVENTF_ABSOLUTE
    
    MOUSEEVENTF_LEFTDOWN = 0x0002 # left button down 
    MOUSEEVENTF_LEFTUP = 0x0004 # left button up 
    MOUSEEVENTF_CLICK = MOUSEEVENTF_LEFTDOWN + MOUSEEVENTF_LEFTUP
    
    def click(x, y):
        #move first
        x = 65536L * x / ctypes.windll.user32.GetSystemMetrics(0) + 1
        y = 65536L * y / ctypes.windll.user32.GetSystemMetrics(1) + 1
        ctypes.windll.user32.mouse_event(MOUSEEVENTF_MOVEABS, x, y, 0, 0)
    
        #then click
        ctypes.windll.user32.mouse_event(MOUSEEVENTF_CLICK, 0, 0, 0, 0)
    

    Update: I didn't test the code below but I think that it should help you to write something to get the child position. Then you can try to click at the correct position.

    CHILD= None
    
    def the_callback(child_hwnd, regex):
        '''Pass to win32gui.EnumWindows() to check all the opened windows'''
        if re.match(regex, win32gui.GetWindowText(child_hwnd)):
            CHILD= child_hwnd
    
    win32gui.EnumChildWindows(hwnd, the_callback, regex)
    
    
    if CHILD:
        (x_tl, y_tl, x_br, y_br) = win32gui.GetWindowRect(CHILD)
    

提交回复
热议问题