0

I'm trying to use XInput API for my game engine (I'm using DirectX11 and C++). I just want to test if a controller is found so I #included and call XInputGetState but I get a strange behavior:

    XINPUT_STATE state;
    ZeroMemory(&state, sizeof(XINPUT_STATE));

    DWORD result;
    for (DWORD i = 0; i < XUSER_MAX_COUNT; i++)
    {
        result = XInputGetState(i, &state);
        if (result == ERROR_SUCCESS)
            ErrorBox(L"found controller on port ");
    }

if I connect a controller the program hangs and freezes, while if I disconnect the controller the game launches. If I step into the code with the debugger the result is that the controller is found and the message box is displayed. Why?

EDIT the problem seems to be in the call to ErrorBox: this function just displays a Message Box using Win32 API.

Luca
  • 1,658
  • 4
  • 20
  • 41

1 Answers1

0

There is a performance hit when you check for a controller that wasn't attached last time you called it because it has to enumerate device, open driver connects, etc. Therefore, you are recommended to round-robin calls to check for new controllers. If you get ERROR_DEVICE_NOT_CONNECTED back, you shouldn't call XInputGetState again for that slot for a little while. For an example of this, see GamePad class in the Directx Tool Ki and the ThrottleRetry function.

In other words, the loop you wrote before is not a good idea to call every frame unless there are XUSER_MAX_COUNT controllers actually connected.

Chuck Walbourn
  • 38,259
  • 2
  • 58
  • 81
  • Yes, but if I comment out the Errorbox it works fine. If I use a OutputDebugString it works fine. So what's the catch with the Win32 API call? – Luca Aug 22 '18 at 14:31
  • That problem is like in how your application handles the main window message loop, which you don't show here. For an example of how to do it for DirectX, see [directx-vs-templates](https://github.com/walbourn/directx-vs-templates/blob/master/d3d11game_win32/Main.cpp). – Chuck Walbourn Aug 22 '18 at 16:53