- 1 year ago
(Windows HID API) HidD_GetPreparsedData() failing in WM_INPUT message handler due to incorrect handle?
If HidD_GetPreparsedData()
is failing in the WM_INPUT message handler with an "incorrect handle" error, it's likely because you're not using the correct handle for the HID device.
The WM_INPUT message handler receives an HRAWINPUT
handle, not the HANDLE
obtained from the CreateFile()
function. To obtain the correct handle for HidD_GetPreparsedData()
, you need to retrieve it using the GetRawInputDeviceInfo()
function.
Here's an example of how you can obtain the correct handle for HidD_GetPreparsedData()
within the WM_INPUT message handler:
cppLRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (message == WM_INPUT)
{
HRAWINPUT hRawInput = reinterpret_cast<HRAWINPUT>(lParam);
UINT dataSize;
// Retrieve the size of the raw input data
GetRawInputData(hRawInput, RID_INPUT, NULL, &dataSize, sizeof(RAWINPUTHEADER));
// Allocate memory to store the raw input data
LPBYTE rawData = new BYTE[dataSize];
// Retrieve the raw input data
GetRawInputData(hRawInput, RID_INPUT, rawData, &dataSize, sizeof(RAWINPUTHEADER));
// Determine the device type (HID, keyboard, etc.)
RAWINPUT* rawInput = reinterpret_cast<RAWINPUT*>(rawData);
if (rawInput->header.dwType == RIM_TYPEHID)
{
// Get the handle for the HID device
HANDLE hDevice = NULL;
UINT size = 0;
GetRawInputDeviceInfo(rawInput->header.hDevice, RIDI_DEVHANDLE, NULL, &size);
if (size > 0)
{
hDevice = CreateFile(L"\\\\.\\HID", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
}
if (hDevice != INVALID_HANDLE_VALUE)
{
// Get the preparsed data
PHIDP_PREPARSED_DATA preparsedData;
if (HidD_GetPreparsedData(hDevice, &preparsedData))
{
// Process the HID data
// Free the preparsed data
HidD_FreePreparsedData(preparsedData);
}
// Close the device handle
CloseHandle(hDevice);
}
}
// Clean up the allocated memory
delete[] rawData;
}
// Process other messages
return DefWindowProc(hWnd, message, wParam, lParam);
}
In this example, within the WM_INPUT message handler, we retrieve the HRAWINPUT
handle from the lParam
parameter. Then we use the GetRawInputDeviceInfo()
function with RIDI_DEVHANDLE
to retrieve the handle for the HID device.
Once we have the correct handle, we can pass it to HidD_GetPreparsedData()
to obtain the preparsed data for further processing. Remember to close the device handle using CloseHandle()
after you're done with it.
Make sure to handle errors appropriately and check for return values to ensure the functions are executed successfully.
Please note that the code snippet provided is a simplified example and may require additional error handling and considerations specific to your use case.