"""Diagnose SendInput delivery.""" import time, ctypes from ctypes import wintypes user32 = ctypes.WinDLL('user32', use_last_error=True) user32.SendInput.argtypes = [wintypes.UINT, ctypes.c_void_p, ctypes.c_int] user32.SendInput.restype = wintypes.UINT ULONG_PTR = ctypes.c_size_t class KEYBDINPUT(ctypes.Structure): _fields_ = [("wVk", wintypes.WORD), ("wScan", wintypes.WORD), ("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), ("dwExtraInfo", ULONG_PTR)] class MOUSEINPUT(ctypes.Structure): _fields_ = [("dx", wintypes.LONG), ("dy", wintypes.LONG), ("mouseData", wintypes.DWORD), ("dwFlags", wintypes.DWORD), ("time", wintypes.DWORD), ("dwExtraInfo", ULONG_PTR)] class HARDWAREINPUT(ctypes.Structure): _fields_ = [("uMsg", wintypes.DWORD), ("wParamL", wintypes.WORD), ("wParamH", wintypes.WORD)] class _I(ctypes.Union): _fields_ = [("mi", MOUSEINPUT), ("ki", KEYBDINPUT), ("hi", HARDWAREINPUT)] class INPUT(ctypes.Structure): _fields_ = [("type", wintypes.DWORD), ("u", _I)] KEYEVENTF_UNICODE = 0x0004 KEYEVENTF_KEYUP = 0x0002 def type_text(text): evts = [] for ch in text: for flag in (KEYEVENTF_UNICODE, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP): inp = INPUT() inp.type = 1 inp.u.ki = KEYBDINPUT(wVk=0, wScan=ord(ch), dwFlags=flag, time=0, dwExtraInfo=0) evts.append(inp) arr = (INPUT * len(evts))(*evts) sent = user32.SendInput(len(evts), ctypes.cast(arr, ctypes.c_void_p), ctypes.sizeof(INPUT)) err = ctypes.get_last_error() return sent, err if __name__ == '__main__': import sys hwnd = int(sys.argv[1]) print("sizeof(INPUT) =", ctypes.sizeof(INPUT)) print("foreground before:", user32.GetForegroundWindow(), "target:", hwnd) user32.SetForegroundWindow(hwnd) time.sleep(0.5) fg = user32.GetForegroundWindow() print("foreground after:", fg) sent, err = type_text('hello') print("SendInput sent:", sent, "last_error:", err) # also try mouse move to see if input pipeline alive p = wintypes.POINT(100, 100) user32.SetCursorPos(100, 100) time.sleep(0.2) user32.GetCursorPos(ctypes.byref(p)) print("cursor:", p.x, p.y) time.sleep(1)