Send keys to a inactive window in Python
11,591
Use (but add error checking)
hwndMain = win32gui.FindWindow("notepad", "prueba.txt: Bloc de notas")
hwndEdit = win32gui.FindWindowEx( hwndMain, 0, "Edit", 0 )
win32api.PostMessage( hwndEdit,win32con.WM_CHAR, ord('x'), 0)
you should add some "sleep" calls if you want to loop posting message :-)
Author by
Admin
Updated on June 20, 2022Comments
-
Admin almost 2 years
I'm trying to press a key in another process from a Python program. I've tried the win32 api, but somehow this code does nothing:
import win32gui import win32con import win32api hwnd = win32gui.FindWindow("notepad", "prueba.txt: Bloc de notas") if(hwnd != 0): win32api.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0) win32api.SendMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0) while(True): win32api.SendMessage( hwnd, win32con.WM_CHAR, ord('x'), 0) else: print("The window is closed")
Of course I want to do this to an inactive window. Any solution or alternatives?
Thanks
-
Admin about 10 yearsThank you guys. What about emulators and games that do not aceppt postmessage? I've tried keybd_event but it's really slow because you must wait like 0.1 seconds.
-
manuell about 10 yearsI you can't or don't want to use PostMessage WM_CHAR (or WM_KEYDOWN), then you are left with SendInput. I m not aware of any "wait" needed by SendInput; See msdn.microsoft.com/en-us/library/windows/desktop/ms646310.aspx If the code posted worked for you, you should accept the answer. You may be able to upvote answers when you'll have more reps.
-
Admin about 10 yearsI think SendInput doesn't work in emulators and games :(
-
manuell about 10 yearsAnyway, if my code helped you to fill Notepad with 'x', you may accept the answer :-) If
keybd_event
works,SendInput
should work as well. And ifSendInput
doesn't work, I am not aware of another solution.