相关文档地址:https://docs.microsoft.com/en-us/windows/win32/xinput/getting-started-with-xinputwindows
须要的头文件:Xinput.hspa
lib 文件:Xinput.lib code
最多同时支持 4 个手柄,因为作工等问题,手柄静止时摇杆可能并不在 0 上,两个 trigger 的数据范围是 0~255,两个摇杆是 -32768~32767。文档
官方文档里还有部分关于 dead zoom 的描述,本例没有考虑get
#include <cstdio> #include <Windows.h> #include <Xinput.h> using namespace std; int GetControllorNum() { DWORD dwResult; int num = 0; for (DWORD i = 0; i < XUSER_MAX_COUNT; i++) //up to 4 controllors { XINPUT_STATE state; ZeroMemory(&state, sizeof(XINPUT_STATE)); // Simply get the state of the controller from XInput. dwResult = XInputGetState(i, &state); if (dwResult == ERROR_SUCCESS) { // Controller is connected printf("one\n"); num++; } else { printf("no\n"); // Controller is not connected } } return num; } int main() { int controllorNum = GetControllorNum(); if (controllorNum > 0) { XINPUT_STATE state, state2; ZeroMemory(&state, sizeof(XINPUT_STATE)); ZeroMemory(&state2, sizeof(XINPUT_STATE)); // Simply get the state of the controller from XInput. DWORD dwResult = XInputGetState(0, &state); while (true) { dwResult = XInputGetState(0, &state2); if (state2.dwPacketNumber != state.dwPacketNumber) { printf("chaned\n"); state = state2; state2.Gamepad.bLeftTrigger; if (state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP) { printf("XINPUT_GAMEPAD_DPAD_UP"); } if (state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_DOWN) { printf("XINPUT_GAMEPAD_DPAD_DOWN"); } if (state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT) { printf("XINPUT_GAMEPAD_DPAD_LEFT"); } if (state.Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) { printf("XINPUT_GAMEPAD_DPAD_RIGHT"); } if (state.Gamepad.wButtons & XINPUT_GAMEPAD_START) { printf("XINPUT_GAMEPAD_START"); } if (state.Gamepad.wButtons & XINPUT_GAMEPAD_BACK) { printf("XINPUT_GAMEPAD_BACK"); } if (state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_THUMB) { printf("XINPUT_GAMEPAD_LEFT_THUMB"); } if (state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_THUMB) { printf("XINPUT_GAMEPAD_RIGHT_THUMB"); } if (state.Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER) { printf("XINPUT_GAMEPAD_LEFT_SHOULDER"); } if (state.Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER) { printf("XINPUT_GAMEPAD_RIGHT_SHOULDER"); } if (state.Gamepad.wButtons & XINPUT_GAMEPAD_A) { printf("XINPUT_GAMEPAD_A"); } if (state.Gamepad.wButtons & XINPUT_GAMEPAD_B) { printf("XINPUT_GAMEPAD_B"); } if (state.Gamepad.wButtons & XINPUT_GAMEPAD_X) { printf("XINPUT_GAMEPAD_X"); } if (state.Gamepad.wButtons & XINPUT_GAMEPAD_Y) { printf("XINPUT_GAMEPAD_Y"); } printf(" pressed\n"); XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE; printf("LeftTrigger: %d\n", state.Gamepad.bLeftTrigger); printf("RightTrigger: %d\n", state.Gamepad.bRightTrigger); printf("ThumbLX: %d\n", state.Gamepad.sThumbLX); printf("ThumbLY: %d\n", state.Gamepad.sThumbLY); printf("ThumbRX: %d\n", state.Gamepad.sThumbRX); printf("ThumbRY: %d\n", state.Gamepad.sThumbRY); } else { printf("no change\n"); } Sleep(1000); } } else { printf("no controllor connected\n"); } return 0; }