- 1 year ago
Raw Input - recive WM_INPUT while window/program is in background
To receive WM_INPUT
messages while your window or program is in the background in Windows, you need to make use of the Raw Input API and set up a raw input device to capture the input regardless of the window focus. Here's an overview of the steps involved:
Register the raw input device: Use the
RegisterRawInputDevices
function to register the raw input device. Specify the device types and flags to capture the desired input. Typically, you would specifyRIDEV_INPUTSINK
as one of the flags to capture input even when your window is not in focus.Process raw input messages: In your message loop, handle the
WM_INPUT
message and process the raw input data using theGetRawInputData
function. This function retrieves the raw input data from the specifiedHRAWINPUT
handle.
Here's a sample code snippet illustrating these steps:
cpp#include <Windows.h>
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int main()
{
// Register the raw input device
RAWINPUTDEVICE rawInputDevice;
rawInputDevice.usUsagePage = 0x01; // Generic desktop controls
rawInputDevice.usUsage = 0x02; // Mouse
rawInputDevice.dwFlags = RIDEV_INPUTSINK;
rawInputDevice.hwndTarget = NULL; // Use NULL to capture input globally
if (!RegisterRawInputDevices(&rawInputDevice, 1, sizeof(RAWINPUTDEVICE)))
{
// Handle registration error
return 1;
}
// Create and set up your window
// ...
// Enter the message loop
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INPUT:
{
// Process raw input
HRAWINPUT hRawInput = reinterpret_cast<HRAWINPUT>(lParam);
UINT dataSize;
// Determine the size of the raw input data
if (GetRawInputData(hRawInput, RID_INPUT, NULL, &dataSize, sizeof(RAWINPUTHEADER)) == -1)
{
// Handle error
break;
}
// Allocate memory for the raw input data
BYTE* dataBuffer = new BYTE[dataSize];
// Retrieve the raw input data
if (GetRawInputData(hRawInput, RID_INPUT, dataBuffer, &dataSize, sizeof(RAWINPUTHEADER)) != dataSize)
{
// Handle error
delete[] dataBuffer;
break;
}
// Process the raw input data
RAWINPUT* rawInput = reinterpret_cast<RAWINPUT*>(dataBuffer);
// ...
// Clean up
delete[] dataBuffer;
break;
}
// Handle other messages as needed
// ...
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
In this example, the raw input device is registered to capture mouse input (usUsagePage
is set to 0x01
and usUsage
is set to 0x02
). The RIDEV_INPUTSINK
flag allows capturing input even when the window is not in focus. The WM_INPUT
message is handled in the window procedure, where the raw input data is retrieved and processed.
Remember to replace the window creation and message loop code with your own window creation logic. Also, handle