I'm trying to automate an application (let's call it app.exe) by sending keystrokes to it. When its main window is open and has focus, doing ALT+F opens the File
menu. I have inspected all the messages posted to the window with Spy++, and I have carefully studied all the parameters.
Then I tried to replicate exactly the same behaviour with PostMessage
(to be sure I'm not sending to the wrong window, I'm even looping on all hWnd
associated to the relevant process ID):
import win32con, win32gui, win32process, win32api, subprocess, time
def get_hwnds_for_pid(pid):
def callback (hwnd, hwnds):
if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
_, found_pid = win32process.GetWindowThreadProcessId(hwnd)
if found_pid == pid:
hwnds.append(hwnd)
return True
hwnds = []
win32gui.EnumWindows(callback, hwnds)
return hwnds
app = subprocess.Popen(["notepad.exe"])
time.sleep(2.0)
for hwnd in get_hwnds_for_pid(app.pid):
win32gui.SetForegroundWindow(hwnd)
win32api.PostMessage(hwnd, win32con.WM_SYSKEYDOWN, 0x12, 0x20380001) # ALT
win32api.PostMessage(hwnd, win32con.WM_SYSKEYDOWN, 0x46, 0x20210001) # F
time.sleep(1.0)
win32api.PostMessage(hwnd, win32con.WM_KEYUP, 0x46, 0xC0210001)
win32api.PostMessage(hwnd, win32con.WM_KEYUP, 0x12, 0x20380001)
Problem: this works when the app is notepad.exe. But it fails with another particular application I'm using (a regular Win32 application, which uses QWidget
for the main window).
To be more precise, I see the _
underline flashing under the first letter of the menu during one second (so the simulated ALT is recognized ; the usual behaviour in Windows application is that the underlined F
appears when you hold the ALT button down) but the F is not recognized.
Once again, I have sent with PostMessage
exactly the same messages to the window as what I have observed with Spy++ when I did the hotkey manually with the real keyboard.
Question: what could prevent a given software app.exe to receive messages posted/injected from another application (=here, my Python script)?