Skip to content

Instantly share code, notes, and snippets.

@superllama
Last active February 25, 2020 00:38
Show Gist options
  • Save superllama/cd44b994bd87bddddc2d4d202170f7fd to your computer and use it in GitHub Desktop.
Save superllama/cd44b994bd87bddddc2d4d202170f7fd to your computer and use it in GitHub Desktop.
a test to mess with the windows gamepad API to show a friend a bare minimum example for collecting joystick data
#pragma comment(lib, "hid.lib")
#include <stdio.h>
#include <Windows.h>
#include <hidsdi.h>
LRESULT CALLBACK dummy_wndproc(HWND wnd, UINT msg, WPARAM wp, LPARAM lp) {
if (msg == WM_INPUT) {
UINT bufferSize;
//get the rawinput data
GetRawInputData((HRAWINPUT)lp, RID_INPUT, 0, &bufferSize, sizeof(RAWINPUTHEADER));
PRAWINPUT rawinput = (PRAWINPUT)malloc(bufferSize);
GetRawInputData((HRAWINPUT)lp, RID_INPUT, rawinput, &bufferSize, sizeof(RAWINPUTHEADER));
//get the preparsed input
GetRawInputDeviceInfo(rawinput->header.hDevice, RIDI_PREPARSEDDATA, 0, &bufferSize);
PHIDP_PREPARSED_DATA preparsedData = (PHIDP_PREPARSED_DATA)malloc(bufferSize);
GetRawInputDeviceInfo(rawinput->header.hDevice, RIDI_PREPARSEDDATA, preparsedData, &bufferSize);
//get the value caps
HIDP_CAPS caps;
HidP_GetCaps(preparsedData, &caps);
USHORT axisCount = caps.NumberInputValueCaps;
PHIDP_VALUE_CAPS valueCaps = (PHIDP_VALUE_CAPS)malloc(sizeof(HIDP_VALUE_CAPS)*axisCount);
HidP_GetValueCaps(HidP_Input, valueCaps, &axisCount, preparsedData);
//get the value of Axis #0 (this was the Y axis on my xbox controller)
int axis_id = 0;
ULONG value = 0;
HidP_GetUsageValue(HidP_Input, valueCaps[axis_id].UsagePage, 0, valueCaps[axis_id].Range.UsageMin, &value, preparsedData, (PCHAR)rawinput->data.hid.bRawData, rawinput->data.hid.dwSizeHid);
printf("%d\n", (LONG)value);
//free the structures allocated
free(valueCaps);
free(preparsedData);
free(rawinput);
}
return 0;
}
int main() {
HWND dummy_wnd = CreateWindowEx(0, "STATIC", "I'm invisible!", 0, 0, 0, 100, 100, 0, 0, 0, 0);
RAWINPUTDEVICE rid;
rid.usUsagePage = 1; //no idea what this is
rid.usUsage = 5; //apparently this tells it it's a gamepad??
rid.dwFlags = RIDEV_INPUTSINK;
rid.hwndTarget = dummy_wnd;
SetWindowLong(dummy_wnd, GWL_WNDPROC, (LONG)dummy_wndproc);
if (!RegisterRawInputDevices(&rid, 1, sizeof(RAWINPUTDEVICE)))
return -1; //it broke D:
MSG msg;
while (GetMessage(&msg, dummy_wnd, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment