asweigart / pyautogui

A cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard.
BSD 3-Clause "New" or "Revised" License
10.22k stars 1.24k forks source link

how to send keystrokes to specific window (even if its not in focus) ? #738

Open divinity76 opened 2 years ago

divinity76 commented 2 years ago

How do i send keystrokes to a specific program/window, even if that program is not currently in focus?

AutoIt has a neat function to send keystrokes to any window, even if it's not in focus, called "ControlSend", documentation https://www.autoitscript.com/autoit3/docs/functions/ControlSend.htm , does pyautogui have something similar to AutoIt's ControlSend?

bersbersbers commented 1 year ago

I would be interested in that, too, but it seems that is not possible. From https://github.com/asweigart/pyautogui#keyboard-and-mouse-control:

All keyboard presses done by PyAutoGUI are sent to the window that currently has focus, as if you had pressed the physical keyboard key.

You may need to focus the window yourself before sending the key, and pray that the user does not quickly change back before the key is actually sent and received.

divinity76 commented 1 year ago

@bersbersbers good news! found a way to do it with "AutoItX" - dll interface to AutoIt functions, sample code sending "Hello World" to a notepad out-of-focus:

import ctypes
autoItXDLL = ctypes.WinDLL("C:\\Program Files (x86)\\AutoIt3\\AutoItX\\AutoItX3_x64.dll")
# AU3_API int WINAPI AU3_ControlSend(LPCWSTR szTitle, LPCWSTR szText, LPCWSTR szControl, LPCWSTR szSendText, int nMode = 0);
autoItXDLL.AU3_ControlSend.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_int]
autoItXDLL.AU3_ControlSend.restype = ctypes.c_int
autoItXDLL.AU3_ControlSend("Untitled - Notepad", None, "Edit1", "Hello World", 0)
bersbersbers commented 1 year ago

@divinity76 thanks, that looks promising! However, it's Windows only and hardly portable, so I rest with my current solution (using pytestqt) for now.