Microsoft Docs

DirectInput Overview

DirectInput is a legacy part of the DirectX API that provides low‑level access to input devices such as keyboards, mice, joysticks, and gamepads.

Although newer Windows APIs (XInput, Windows.Gaming.Input) cover most gamepad scenarios, DirectInput remains useful for specialized hardware and legacy applications.

Getting Started

Prerequisites

Initialize DirectInput

#include <dinput.h>
#pragma comment(lib, "dinput8.lib")
#pragma comment(lib, "dxguid.lib")

LPDIRECTINPUT8 gDirectInput = nullptr;

HRESULT InitDirectInput(HINSTANCE hInst)
{
    HRESULT hr = DirectInput8Create(
        hInst,
        DIRECTINPUT_VERSION,
        IID_IDirectInput8,
        (void**)&gDirectInput,
        nullptr);
    return hr;
}

Core Interfaces

IDirectInput8

Created via DirectInput8Create. Provides methods to enumerate devices and create device objects.

IDirectInputDevice8

Represents an input device. Key methods:

Enumerations

enum DIENUMSTOP
{
    DIENUM_STOP = 0,
    DIENUM_CONTINUE = 1
};

enum DIPROP
{
    DIPROP_GUIDANDPATH = 0x0002,
    DIPROP_VIDPID      = 0x0003,
    // ...
};

Key Structures

typedef struct DIDEVICEINSTANCE
{
    DWORD   dwSize;
    GUID    guidInstance;
    GUID    guidProduct;
    DWORD   dwDevType;
    WCHAR   tszInstanceName[260];
    WCHAR   tszProductName[260];
    // …
} DIDEVICEINSTANCE, *LPDIDEVICEINSTANCE;

Sample: Keyboard Input

#include <windows.h>
#include <dinput.h>

LPDIRECTINPUTDEVICE8 gKeyboard = nullptr;

bool InitKeyboard(HINSTANCE hInst, HWND hWnd)
{
    HRESULT hr = gDirectInput->CreateDevice(GUID_SysKeyboard, &gKeyboard, nullptr);
    if (FAILED(hr)) return false;

    hr = gKeyboard->SetDataFormat(&c_dfDIKeyboard);
    if (FAILED(hr)) return false;

    hr = gKeyboard->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
    if (FAILED(hr)) return false;

    return SUCCEEDED(gKeyboard->Acquire());
}

void UpdateKeyboard()
{
    BYTE keystate[256];
    if (SUCCEEDED(gKeyboard->GetDeviceState(sizeof(keystate), keystate)))
    {
        if (keystate[DIK_SPACE] & 0x80) {
            OutputDebugStringA("Space pressed\\n");
        }
    }
}