'How do I send a click event without moving my mouse on Win?

I'm trying to write a function to allow me to send a left click to x, y co-ordinates on screen without my mouse cursor moving.

I've read through the send message documentation and the mouse input notification documentation and I've come up with a few different approaches, none of which work. And none throw an error.

I'm using win32gui.FindWindow to get the hwnd and then I've tried using both PostMessage and SendMessage to perform the click, none so far work.

import win32api, win32gui, win32con

def control_click(x, y):

    hWnd = win32gui.FindWindow(None, "Pixel Starships")
    l_param = win32api.MAKELONG(x, y)

    if button == 'left':
        win32gui.PostMessage(hWnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, l_param)
        win32gui.PostMessage(hWnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, l_param)
   
control_click(526, 694)

def click(x, y):
    hWnd = win32gui.FindWindow(None, "Pixel Starships")
    lParam = win32api.MAKELONG(x, y)

    win32api.SendMessage(hWnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
    win32api.SendMessage(hWnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, lParam)

click(526,694)

def leftClick(pos):
    hWnd = win32gui.FindWindow(None, "Pixel Starships")
    lParam = win32api.MAKELONG(pos[0], pos[1])

    win32gui.SendMessage(hWnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam) 
    win32gui.SendMessage(hWnd, win32con.WM_LBUTTONUP, 0, lParam)

leftClick([526,964])

What do I need to do to get this function to work?



Solution 1:[1]

Could this work?

win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)

I would also recommend trying pyautogui. It might help.

Solution 2:[2]

I would also recommend using pyautogui because afaik it has a function to generate a click at a specific position without changing current cursor location.

Also you probably want to have a couple of milliseconds between button-down and button-up function because windows sometimes tend to not register the second button function due to beeing to fast after the button down. Additionally if this is for a game (pixel starships), you want to randomize this milliseconds waitingframe. Otherwise you might run into anti-bot checks and get dispelled/banned from the game server if pixel starships implements those.

Solution 3:[3]

Maybe you can try with Pywinauto is another library similar to PyAutoGUI, but allows you to manipulate apps via her control identifier.

import pywinauto
app = pywinauto.Application().connect(path='notepad.exe')
app.UntitledNotepad.MenuSelect("Edit->Replace")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Seth Edwards
Solution 2 4lexKidd
Solution 3