Search code examples
c#.netperformancekeypresssendkeys

Does a fast and predictable alternative to `SendKeys` exist?


I'm trying to program an AI for online games which works by grabbing a screen region of the game area, analyzing the pixels, and then responding with a sequence of keypresses. Basically, it goes like this:

  • Program grabs picture of current frame
  • Program analyzes pixel data and plans accordingly
  • Program sends firefox appropriate keypresses to respond.

I'm currently having problems at step 3 - sending the keypresses. Since I'm building an AI for games, it must send the keypresses realtime. However, I'm noticing with SendKeys.Send()...

  • There's an apparent delay between when I make the request and when firefox executes it
  • It's unpredictable and slow, the keypresses are almost never executed on time
  • Movement is slow and choppy, because there are large gaps in between each processed keypress

Is there any way to predictably send keypress events to a program (such as firefox) realtime? Like when I think about simulating keypresses with a program, I'm thinking of a command that would do the exact same thing as when I press a key on my keyboard, not an unreliable and delayed method to send keypresses to whatever is currently focused. It would be great if anybody had an easy solution to this problem, or maybe any input on what I can do differently? Thanks!


Solution

  • The Windows Input Simulator wrapper library uses SendInput rather than SendKeys.

    SendInput is generally the preferred method to send keystrokes and mouse clicks because of its superior speed and reliability. Under most conditions, SendInput is nearly instantaneous, even when sending long strings. Since SendInput is so fast, it is also more reliable.

    AutoHotKey Send