Foreground
SendInput can be used if the window is active. There are a few things worth noting about this implementation: A real-world use case will need to be more complex for extended/system keys. SendInput also sends the
Low Level Keyboard Hook Flag: INJECTED (), which will give the target application an opportunity to detect the injected input. There are bots out there which use SendInput and have not caught a ban, but I don't personally feel comfortable doing this.
As for specifically why your example isn't working, some of the properties of ip might be overwritten when it is passed into SendInput, try setting wVk, type and ki after the first call to SendInput is made; every example I can find explicitly sets each property before each call.
Background
There are many restrictions to sending input to background/minimized windows (or active windows) with SendMessage/PostMessage.
First, when sending input with SendMessage or PostMessage the physical state of the device persists and receives priority in some cases. This means if you emulate input and the target application calls GetKeyState it will return a negative result unless the user happens to be pressing the key at the time the input is emulated.
Similarly, if you try to emulate movement such as running, turning (like your SendInput example), backpedaling or strafing by sending multiple WM_CHAR messages as you would see with Spy++ or a similar message loop monitoring tool, it will not work. You cannot emulate repeat/"held down" buttons.
This problem also manifests itself with emulation of mouse input. I believe the mouse position will always reflect the actual position even if you have crafted the messages to specify otherwise, because of the same physical status problem.
So you can emulate keyboard keypresses to background windows, but as for holding keys or mouse manipulation, you're pretty much out of luck.
There only appear to be a few possible solutions, none of which are straightforward, easy and background compatible:
- DDK: A filter (to manipulate emulated messages)
- DDK: A driver (to emulate them closer to the kernel, instead of via WINAPI)
Both of those are fairly heavy topics and don't appear to be well-documented openly on the Internet. You can check out if you're interested in digging deeper.- SendInput to active window, possibly with LLKHF_INJECTED/LLMHF_INJECTED patched out of kernel (heh)
Hopefully this is helpful to you.