How can I send keyboard input to a OpenGL/DirectX game window?

后端 未结 2 1175
名媛妹妹
名媛妹妹 2021-01-25 21:40

How can I simulate a keypress in a game window (using any programming language in Windows)?

AutoHotKeys Scripts and .NET SendKeys functions do not work...

相关标签:
2条回答
  • 2021-01-25 22:31

    Any programming language? My recommendation is to write up a little app in C or C++ (although you could also do this in a .NET app with P/Invoke).

    Specifically, you're looking for the SendInput function from the Win32 API, which can send low-level keyboard and mouse input to an application. It does this in terms of an INPUT structure that contains the information you want to send.

    Of course, use of this function is subject to UIPI, which means that the application you're injecting input into must be running at an equal or lesser integrity level than the application that is doing the injecting.

    However, since this function is generally what SendKeys uses under the covers, that last little caveat might be why it isn't working. It's hard to say exactly; you don't tell us what you mean by "do not work".

    0 讨论(0)
  • 2021-01-25 22:45

    Using AutoIt!3 (which is quite similar to AutoHotKeys), you'd use Send() (http://www.autoitscript.com/autoit3/docs/functions/Send.htm), but make sure to have the game window active (WinActivate()) before you do.

    I've used this to interact with Second Life (which uses OpenGL) succesfully. You may require a Sleep() period between simulated key presses, since not all games implement good keyboard buffers.

    If this doesn't work, the game is probably accessing the hardware drivers directly, and your only option is to hook into the keyboard drivers.

    If the game is polling asynchonously, you want to use the down and up modifiers flags:

    Send("{left down}")  ; hold down the LEFT key
    Sleep(10)            ; keep it pressed for 10 milliseconds
    Send("{left up}")    ; release the LEFT key
    

    Figuring out how long to keep the key pressed depends entirely on how frequently the program you're trying to control is polling the keyboard; no way to know for sure.

    0 讨论(0)
提交回复
热议问题