DirectX Input

The DirectX Input component provides a unified interface for handling input from various devices, including keyboards, mice, joysticks, gamepads, and other human interface devices (HIDs). It simplifies the process of gathering input data, allowing developers to create more immersive and interactive applications and games.

Key Concepts

Core Components and Interfaces

DirectInput utilizes several key COM interfaces:

Getting Started with DirectInput

The basic workflow for using DirectInput involves:

  1. Initialization: Create an instance of the IDirectInput8 interface.
  2. Device Enumeration: Enumerate available devices and filter for the ones you need (e.g., keyboard, mouse, gamepad).
  3. Device Creation: Create an IDirectInputDevice8 object for each desired device.
  4. Device Configuration: Set device properties, such as cooperative levels (exclusive/shared access) and device format (mapping input axes and buttons).
  5. Device Acquisition: Acquire the devices to begin receiving input.
  6. Input Polling/Event Handling: Periodically poll devices for their current state or set up notification mechanisms for input events.
  7. Data Processing: Interpret the input data to control game logic or application behavior.
  8. Cleanup: Release device objects and the DirectInput object when done.

Example: Acquiring Keyboard State

The following is a conceptual outline of how to acquire keyboard state:

            
#include <dinput.h>

// ... initialization ...

IDirectInput8* pDI = NULL;
DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&pDI, NULL);

IDirectInputDevice8* pKeyboard = NULL;
pDI->CreateDevice(GUID_SysKeyboard, &pKeyboard, NULL);

// Set cooperative level
pKeyboard->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);

// Set data format
pKeyboard->SetDataFormat(&c_dfDIKeyboard);

// Acquire the device
pKeyboard->Acquire();

// Later, in your game loop:
DIDEVCAPTUREED_DEVICE_STATE keyboardState;
if (SUCCEEDED(pKeyboard->GetDeviceState(sizeof(DIDEVCAPTUREED_DEVICE_STATE), &keyboardState))) {
    if (keyboardState.rgbButtons[DIK_SPACE] & 0x80) {
        // Space bar is pressed
    }
}

// ... cleanup ...
            
            

Best Practices