Windows programming: Accessing raw input

There is a way to access every device's raw input. Basically there are three steps:


  1. Register to the input(s)
  2. Get the raw data.
  3. Process it

Register

To register to a device's input you have to call "RegisterInputDevice", which receives a    RAWINPUTDEVICE structure:

//http://msdn.microsoft.com/en-us/library/windows/desktop/ms645565(v=vs.85).aspxRAWINPUTDEVICE Rid[2];
Rid[0].usUsagePage = 0x01;
Rid[0].usUsage = 0x06; //keyboard?
Rid[0].dwFlags = RIDEV_INPUTSINK; //Receives the input even if the window is not currently active
Rid[0].hwndTarget = hWnd; //RIDEV_INPUTSINK needs a window handler, can be null otherwise
Rid[1].usUsagePage = 0x01;
Rid[1].usUsage = 0x02; //mouse?
Rid[1].dwFlags = RIDEV_NOLEGACY;   // adds HID mouse and also ignores legacy mouse messages
Rid[1].hwndTarget = 0;
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms645600(v=vs.85).aspxif( RegisterRawInputDevices(Rid, 2, sizeof(Rid[0])) == FALSE)
return FALSE;

Get the raw data


Simply calling GetRawInputData twice with the proper parameters, the first one to know the amount of data to be read and the second one to read the data:
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms645596(v=vs.85).aspx
LPBYTE lpb = new BYTE[dwSize];
if (lpb == NULL)
{
return 0;
}
if (GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize,
sizeof(RAWINPUTHEADER)) != dwSize )
OutputDebugString (TEXT("GetRawInputData does not return correct size !\n"));
RAWINPUT* raw = (RAWINPUT*)lpb;
 UINT dwSize;
GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize, sizeof(RAWINPUTHEADER));


Process the data

For example, I am going to write the keyboard info into a file and show some mouse info on the screen:

if (raw->header.dwType == RIM_TYPEKEYBOARD)
{
HRESULT hResult = StringCchPrintf(szTempOutput, STRSAFE_MAX_CCH, TEXT("%c"), raw->data.keyboard.VKey);
if (FAILED(hResult))
{
// TODO: write error handler
}
if (raw->data.keyboard.Flags == RI_KEY_MAKE) //Only saving the key down
{
fprintf (pFile, "%c", szTempOutput); OutputDebugString(szTempOutput);
}
}
else if (raw->header.dwType == RIM_TYPEMOUSE)
{
HRESULT hResult = StringCchPrintf(szTempOutput, STRSAFE_MAX_CCH, TEXT("Mouse: usFlags=%04x ulButtons=%04x usButtonFlags=%04x usButtonData=%04x ulRawButtons=%04x lLastX=%04x lLastY=%04x ulExtraInformation=%04x\r\n"),
raw->data.mouse.usFlags,
raw->data.mouse.ulButtons,
raw->data.mouse.usButtonFlags,
raw->data.mouse.usButtonData,
raw->data.mouse.ulRawButtons,
raw->data.mouse.lLastX,
raw->data.mouse.lLastY,
raw->data.mouse.ulExtraInformation);
if (FAILED(hResult))
{
       TODO: write error handler
}
OutputDebugString(szTempOutput);
}
delete[] lpb; 

Comentarios

Entradas populares