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 :-)

Share:
11,591
Admin
Author by

Admin

Updated on June 20, 2022

Comments

  • Admin
    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
    Admin about 10 years
    Thank 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
    manuell about 10 years
    I 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.as‌​px 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
    Admin about 10 years
    I think SendInput doesn't work in emulators and games :(
  • manuell
    manuell about 10 years
    Anyway, 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 if SendInput doesn't work, I am not aware of another solution.