PostMessage with WM_LBUTTONDOWN in inactive, unfocused, minimized window

Viewed 62

I am writing a program to automate actions in the game.

I can send a keystroke to a minimized, unfocused, inactive window (It works correctly):

from ctypes import windll
import win32con

hwnd = win32gui.FindWindow(None, "Example Window Name")
windll.user32.PostMessageA(hwnd, win32con.WM_KEYDOWN, win32con.VK_SPACE, 0)

But when I try to send a mouse click, I get a response of 1 (everything worked correctly), but nothing happened in the window

from ctypes import windll
import win32con

hwnd = win32gui.FindWindow(None, "Example Window Name")
x,y = (0,0) # doesn't matter
windll.user32.PostMessageA(hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, win32api.MAKELONG(x, y)) #return 1
time.sleep(0.001) #try any timings
windll.user32.PostMessageA(hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, win32api.MAKELONG(x, y)) #return 1

My problem has the following solution

from ctypes import windll
import win32con
import win32process
import win32gui
import win32api

hwnd = win32gui.FindWindow(None, "Example Window Name")
x,y = (0,0) # doesn't matter
remote_thread, _ = win32process.GetWindowThreadProcessId(hwnd)
win32process.AttachThreadInput(win32api.GetCurrentThreadId(), remote_thread, True)
win32gui.SetFocus(hwnd)

windll.user32.PostMessageA(hwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, win32api.MAKELONG(x, y))
time.sleep(0.001)
windll.user32.PostMessageA(hwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, win32api.MAKELONG(x, y))

I need to click on a window, but I don't want it to be in focus.

I tried to remember the handle of the window in which the user is now, and then quickly switch the focus to the one I need and return it to the past, but due to the delay it will not look correct.

As a result, I need a function that will allow me to click on the given coordinates in the unfocused, inactive, minimized window, knowing its hwnd. At the moment of pressing, the user should be able to use the mouse, keyboard, other windows.

Additional information: Window is an unreal engine game. My program run as administrator. Current technology stack PyWin32, ctypes(user32.dll). I also tried functions from ahk and autoit, for my window they don't work. pywinauto cannot attach to process.

I repeat this is very important!! window may be minimized, inactive, unfocused

0 Answers
Related