Sample Function 1: DI_Init

This application-defined sample function creates a DirectInput object, initializes it, and retrieves the necessary interface pointers, assigning them to global variables. When initialization is complete, it acquires the device.

If any part of the initialization fails, this function calls the DI_Term application-defined sample function to deallocate DirectInput objects and interface pointers in preparation for terminating the program. (See Sample Function 2: DI_Term.)

Besides creating the DirectInput object, the DI_Init function performs the tasks discussed in the following tutorial steps:

Here is the DI_Init function:

// HINSTANCE            g_hinst;    //initialized application instance
// HWND                 g_hwndMain; //initialized application window
LPDIRECTINPUT        g_lpDI; 
LPDIRECTINPUTDEVICE  g_lpDIDevice; 
 
BOOL WINAPI DI_Init() 
{ 
    HRESULT hr; 
 
    // Create the DirectInput object. 
    hr = DirectInputCreate(g_hinst, DIRECTINPUT_VERSION, 
                           &g_lpDI, NULL); 
    if FAILED(hr) return FALSE; 
 
    // Retrieve a pointer to an IDirectInputDevice interface 
    hr = g_lpDI->CreateDevice(GUID_SysKeyboard, &g_lpDIDevice, NULL); 
    if FAILED(hr) 
    { 
        DI_Term(); 
        return FALSE; 
    } 
 
// Now that you have an IDirectInputDevice interface, get 
// it ready to use. 
 
    // Set the data format using the predefined keyboard data 
    // format provided by the DirectInput object for keyboards. 
    hr = g_lpDIDevice->SetDataFormat(&c_dfDIKeyboard); 
    if FAILED(hr) 
    { 
        DI_Term(); 
        return FALSE; 
    } 
 
    // Set the cooperative level 
    hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain, 
                       DISCL_FOREGROUND | DISCL_NONEXCLUSIVE); 
    if FAILED(hr) 
    { 
        DI_Term(); 
        return FALSE; 
    } 
 
    // Get access to the input device. 
    hr = g_lpDIDevice->Acquire(); 
    if FAILED(hr) 
    { 
        DI_Term(); 
        return FALSE; 
    } 
 
    return TRUE; 
}