I am trying to connect a USB controller to my computer and be able to read what buttons are pressed. After looking at Microsoft documentation, I tried making a raw input system. However, I can't seem to understand the documentation and can't find any other good documentation. Below is my best effort. What am I doing wrong?
#include<iostream>
#include<string>
#include<Windows.h>
LRESULT WINAPI WindProc(HWND hwnd, UINT msg, WPARAM wpar, LPARAM lpar)
{
switch (msg)
{
case WM_CREATE:
{
RAWINPUTDEVICE rid;
rid.usUsagePage = 0x0001;
rid.usUsage = 0x0004;
rid.dwFlags = 0;
rid.hwndTarget = hwnd;
if (RegisterRawInputDevices(&rid, 1, sizeof(RAWINPUTDEVICE)) == false)
{
std::cout << "Failed to register raw input device\n";
exit(-1);
}
break;
}
case WM_INPUT:
{
UINT Size = 0;
if (GetRawInputData((HRAWINPUT)lpar, RID_INPUT, NULL, &Size, sizeof(RAWINPUTHEADER)) != 0)
{
std::cout << "error in getting raw input data\n";
exit(-1);
}
LPBYTE lpb = new BYTE[Size];
if (lpb == nullptr)
{
std::cout << "error creating lpb\n";
exit(-1);
}
if (GetRawInputData((HRAWINPUT)lpar, RID_INPUT, &lpb, &Size, sizeof(RAWINPUTHEADER)) != Size)
{
std::cout << "Does not return correct size\n";
exit(-1);
}
RAWINPUT* raw = (RAWINPUT*)lpb;
if (raw->header.dwType == RIM_TYPEHID)
{
std::cout << raw->data.hid.bRawData << std::endl;
}
delete[] lpb;
break;
}
}
return DefWindowProc(hwnd, msg, wpar, lpar);
}
int main() {
const wchar_t* name = L"MY_WND";
WNDCLASS wc = { };
wc.lpfnWndProc = WindProc;
wc.lpszClassName = name;
if (!RegisterClass(&wc))
{
terminate();
}
HWND hwnd = CreateWindow(name, name, WS_OVERLAPPEDWINDOW, 0, 0, 800, 600, NULL, 0, 0, 0);
ShowWindow(hwnd, SW_SHOW);
SetFocus(hwnd);
MSG msg = { };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}