[Python] win32gui - Unable to SendMessage unless window is focused

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    Hi I'm trying to create a simple script that types the letter A into a window.

    In this case, the window is Old School Runescape. Yes it is a game.

    Here's the little code I use.

    import win32gui, win32ui, win32con, win32api
    import time

    if __name__ == "__main__":
    window_name = "Old School RuneScape"
    hwnd = win32gui.FindWindow(None, window_name)

    win = win32ui.CreateWindowFromHandle(hwnd)

    while True:
    print("Sending")
    win.SendMessage(win32con.WM_CHAR, ord('A'), 0)
    time.sleep(2)


    This code works on various other programs. However, particularly for this, it doesn't work unless the game window is in focus.

    I suspected that there might be an inner window as this is a game, so I did a little check and found that there's an inner window.:

    {'SunAwtCanvas': 1771602}


    But, it still doesn't work when I try to send to the Main / Inner window.

    I followed the documentation on Microsoft's site as well as researched quite a bit on Stackoverflow for some help but to no avail.

    Does anyone know what might be the issue?

    Update 1
    I tried using

    win.PostMessage(win32con.WM_CHAR, 0x44, 0)


    Still, it only works when the window is focused.

    Continue reading...

Compartilhe esta Página