SendInput to background window

6.2k Views Asked by At

I want to send the mouse and keyboard input, which is recieved from android client, to games running on windows. SendInput works for almost all games I have worked so far. But for SendInput to work the game must be a foreground window.

To solve that I used PostMessage(hwnd,...) with hwnd being handle to the game window. But this does not work if game is using DirectInput. That was solved by hooking GetDeviceState. Now another game I started working on is using WM_INPUT or raw input and I have to create raw input to make it work.

According to this MSDN Article

DirectInput is a set of API calls that abstracts input devices on the system. Internally, DirectInput creates a second thread to read WM_INPUT data, and using the DirectInput APIs will add more overhead than simply reading WM_INPUT directly.

directInput works using WM_INPUT.

The SendInput function inserts the events in the INPUT structures serially into the keyboard or mouse input stream. These events are not interspersed with other keyboard or mouse input events inserted either by the user (with the keyboard or mouse) or by calls to keybd_event, mouse_event, or other calls to SendInput.

So SendInput is also providing abstraction.

All I want is to send the input to application independently even when its window is not in focus. That way I will be able to send input to multiple games at once. Is there any way to achieve this using one higher level API call like SendInput? Can this be done with SendInput? Is there any C/C++ library for that?

1

There are 1 best solutions below

1
On

When registering your input device using the RAWINPUTDEVICE structure, set dwFlags = RIDEV_EXINPUTSINK to receive input when the process is in the background.

Example:

RAWINPUTDEVICE rid;

rid.usUsagePage = 1;
rid.usUsage     = 4;    // Joystick
rid.dwFlags     = RIDEV_EXINPUTSINK;
rid.hwndTarget  = window;

if (!RegisterRawInputDevices(&rid, 1, sizeof(RAWINPUTDEVICE)))
    return -1;