This code (inspired from Which is the easiest way to simulate keyboard and mouse on Python?) opens a Notepad and send the keys A, B, C, D, ..., Z every second:
import win32com.client, time
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run('Notepad')
time.sleep(1)
shell.AppActivate("Notepad")
for i in range(65,91):
shell.SendKeys(chr(i))
time.sleep(1)
I would like to let this operation continue in background, continue my work on the computer, and have the keystrokes sent to Notepad (in background).
Problem: if I open another application (example: browser) in the meantime, the keystrokes are sent ... to the currently active window, which I dont't want!
Question: how to have Python send the keystrokes to notepad.exe only, even if this application is not in foreground?
Context: I'm automating some long task requiring that my Python script sends keystrokes to app.exe
(in background) during maybe 15 minutes, but I'd like to do something else with the computer in the meantime.
Note: More generally, the use case I'm interested in is the case where the process app.exe might open dialogs, close dialogs, open other windows, so the solution should be able to send the keystrokes to the active window of the process. Thus a solution with a fixed hWnd like here doesn't work directly.