Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

How to send key down and key up events to inactive game window in python?

I am trying to make a program that will send key events to multiple windows at the same time. Note: the windows I am trying to send key events to are games

I managed to use win32api.PostMessage, but that can't hold the key down + it doesn't work for games. PostMessage works for notepad windows, but not for games. I am using python with win32 modules but any other modules are welcome.

Here is what I have:

def on_press_forward(key):
    for instance in game_instances:
        hwndChild = win32gui.GetWindow(instance, win32con.GW_CHILD)
        letter = get_key_code(key)
        if not letter == 0:
            temp = win32api.PostMessage(hwndChild, win32con.WM_CHAR, int(letter, 16), 0)

The function above is automatically called when a key is pressed. The key variable is a pynput object. game_instances is a list with hwnd of all game windows. get_key_code returns a hex value that corresponds to the letter provided ( because PostMessage requires it to be in hex ), or returns 0 if the key in not a letter ( for ex. shift ).

What other function to use except PostMessage? Thanks for any help!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...