How to use the namespace Windows.Gaming.Input in C++ without using UWP?

4k views Asked by At

I have a large C++ game project in which I want to add support for Xbox One controllers. I tried using the Windows.Gaming.Input namespace. However, it seems that this is only available for UWP projects. Is this true?

If this is the case, would it be easy to port an existing SDL engine to UWP?

1

There are 1 answers

2
Sunius On

You can call into Windows.Gaming.Input just fine from desktop applications - not sure where you got the idea that it's only available to UWP applications. Just include the header and use it. Here's the sample code for printing button states on all the gamepads:

#include <assert.h>
#include <cstdint>
#include <iostream>
#include <roapi.h>
#include <wrl.h>
#include "windows.gaming.input.h"

using namespace ABI::Windows::Foundation::Collections;
using namespace ABI::Windows::Gaming::Input;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;

#pragma comment(lib, "runtimeobject.lib")

int main()
{
    auto hr = RoInitialize(RO_INIT_MULTITHREADED);
    assert(SUCCEEDED(hr));

    ComPtr<IGamepadStatics> gamepadStatics;
    hr = RoGetActivationFactory(HStringReference(L"Windows.Gaming.Input.Gamepad").Get(), __uuidof(IGamepadStatics), &gamepadStatics);
    assert(SUCCEEDED(hr));

    ComPtr<IVectorView<Gamepad*>> gamepads;
    hr = gamepadStatics->get_Gamepads(&gamepads);
    assert(SUCCEEDED(hr));

    uint32_t gamepadCount;
    hr = gamepads->get_Size(&gamepadCount);
    assert(SUCCEEDED(hr));

    for (uint32_t i = 0; i < gamepadCount; i++)
    {
        ComPtr<IGamepad> gamepad;
        hr = gamepads->GetAt(i, &gamepad);
        assert(SUCCEEDED(hr));

        GamepadReading gamepadReading;
        hr = gamepad->GetCurrentReading(&gamepadReading);
        assert(SUCCEEDED(hr));

        std::cout << "Gamepad " << i + 1 << " buttons value is: " << gamepadReading.Buttons << std::endl;
    }

    return 0;
}