"""Try forcing foreground via AttachThreadInput, then test SendInput.""" import ctypes, sys, time from ctypes import wintypes user32 = ctypes.WinDLL('user32', use_last_error=True) kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) user32.AttachThreadInput.argtypes = [wintypes.DWORD, wintypes.DWORD, wintypes.BOOL] user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)] user32.GetWindowThreadProcessId.restype = wintypes.DWORD kernel32.GetCurrentThreadId.restype = wintypes.DWORD def force_foreground(hwnd): tid_target = user32.GetWindowThreadProcessId(hwnd, None) tid_self = kernel32.GetCurrentThreadId() print('threads: target', tid_target, 'self', tid_self) attached = user32.AttachThreadInput(tid_self, tid_target, True) print('AttachThreadInput:', attached, 'err', ctypes.get_last_error()) user32.ShowWindow(hwnd, 9) # SW_RESTORE user32.BringWindowToTop(hwnd) ok = user32.SetForegroundWindow(hwnd) print('SetForegroundWindow:', ok, 'err', ctypes.get_last_error()) user32.SetFocus(hwnd) time.sleep(0.5) print('foreground now:', user32.GetForegroundWindow(), 'active:', user32.GetActiveWindow()) print('AttachThreadInput(detach):', user32.AttachThreadInput(tid_self, tid_target, False)) if __name__ == '__main__': force_foreground(int(sys.argv[1]))