- 1 year ago
How to distinguish real keyboard or mouse input from command input like 'SendInput' by using hRawInput
To distinguish between real keyboard/mouse input and synthetic input generated by functions like SendInput
using hRawInput
in Windows, you can follow these steps:
Register for Raw Input: Register your application to receive raw input using the
RegisterRawInputDevices
function. This allows you to receive raw input from devices such as keyboards and mice.Process Raw Input: When you receive raw input events, check the
hDevice
field of theRAWINPUTHEADER
structure. This field represents the handle of the device that generated the input.Differentiate Input Sources: Use the
GetRawInputDeviceInfo
function to retrieve information about the input device based on its handle (hDevice
). You can examine the device information to differentiate between real physical devices (keyboard/mouse) and synthetic input devices.Here's an example snippet to differentiate between keyboard and synthetic input using
hRawInput
:cpp#include <Windows.h>
bool IsRealKeyboardInput(HANDLE hRawInput)
{
UINT size;
GetRawInputDeviceInfo(hRawInput, RIDI_DEVICENAME, nullptr, &size);
if (size > 0)
{
wchar_t* deviceName = new wchar_t[size];
if (GetRawInputDeviceInfo(hRawInput, RIDI_DEVICENAME, deviceName, &size) > 0)
{
// Compare the device name with known synthetic devices
// e.g., "SendInput", "Virtual", etc.
if (wcsstr(deviceName, L"SendInput") != nullptr ||
wcsstr(deviceName, L"Virtual") != nullptr)
{
delete[] deviceName;
return false; // Synthetic input
}
}
delete[] deviceName;
}
return true; // Real keyboard input
}
// Usage example
LRESULT CALLBACK RawInputHandler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (message == WM_INPUT)
{
HRAWINPUT hRawInput = reinterpret_cast<HRAWINPUT>(lParam);
if (hRawInput)
{
if (IsRealKeyboardInput(hRawInput))
{
// Process real keyboard input
// ...
}
else
{
// Process synthetic input
// ...
}
}
// Cleanup
DefRawInputProc(&hRawInput, 1, sizeof(RAWINPUTHEADER));
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
In the above example, the
IsRealKeyboardInput
function checks the device name associated with the givenhRawInput
handle. If the device name contains certain keywords (such as "SendInput" or "Virtual"), it indicates that the input is synthetic and not from a physical keyboard.Note that this approach relies on comparing the device name with known patterns, and it may not be foolproof as device names can vary. You may need to adjust and customize the comparison logic based on your specific requirements and synthetic device names.
By differentiating between real keyboard/mouse input and synthetic input, you can handle them differently as per your application's needs.