'How to simulate click to specific background window (not in focus)?

I am trying to click a window that is in the background (without focus), without moving the mouse cursor (so I can continue to use my screen and mouse normally).

Using Python win32gui the application isn't registering the click. Using AutoHotkey I couldn't find a way to simulate the click (I only managed to write to it because I didn't find anything like win.click or ahk.controlclick). Can I do it with AutoHotkey or is there anything else I can use?

The code which doesn't work:

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

    hWnd1= win32gui.FindWindowEx(hWnd, None, None, None)
    win32gui.SendMessage(hWnd1, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, lParam)
    win32gui.SendMessage(hWnd1, win32con.WM_LBUTTONUP, None, lParam)


Solution 1:[1]

A trivial approach that is not very robust, is using PyAutoGUI you just need to

  1. install it using pip install pyautogui or if you are using poetry, you can install by using the following command poetry add pyautogui

  2. then use the function pyautogui.click(x, y) and pass int values to them

  3. you can also move the cursor to pyautogui.moveTo(x,y) absolute movement or you can move it relative to the current cursor position by using pyautogui.move(x, y)

A more robust approach is to use an image of where you want to move the mouse and use pyautogui.locateOnScreen('path_to_image')

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 ElSheikh