I am using the below code to send keys to an inactive window using python on windows:
import win32gui
import win32con
import win32api
import time
import win32com.client
def send_key(hwnd, key):
win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, key, 0)
time.sleep(1)
win32api.PostMessage(hwnd, win32con.WM_KEYUP, key, 0)
def send_key_comb(hwnd, key1, key2):
win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, key1, 0)
time.sleep(1)
win32api.PostMessage(hwnd, win32con.WM_KEYDOWN, key2, 0)
time.sleep(1)
win32api.PostMessage(hwnd, win32con.WM_KEYUP, key1, 0)
time.sleep(1)
win32api.PostMessage(hwnd, win32con.WM_KEYUP, key2, 0)
time.sleep(1)
def get_window_handle():
hwndMain = win32gui.FindWindow(None, "MyApp - V2.2")
#
# Notepad example - working
#
# hwndMain = win32gui.FindWindow(None, "*Untitled - Notepad")
#
return hwndMain
def send_str(hwnd, strng):
for c in strng:
send_key(hwnd, ord(c))
def send_tabs(hwnd, n):
for i in range(n):
send_key(hwnd, win32con.VK_TAB)
if __name__ == "__main__":
hwnd = get_window_handle()
send_str(hwnd, "abcd")
#
# Tried the below also, but not working
#
# child = win32gui.GetWindow(hwnd, win32con.GW_CHILD)
# send_str(child, "abcd")
This script is sending "11223344" to notepad application, but it is not sending keys to my specific application window
I also noticed that the script is able to send tabs to the specific application window, but it fails while sending the characters
Not sure what could be wrong. Any pointers would be very helpful