Platform SDK: DirectX

Sample Function 1: DI_Init

[Visual Basic]

The information in this topic pertains only to applications written in C++. See DirectInput Visual Basic Tutorials.

[C++]

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:

/ * The following variables are presumed initialized:
HINSTANCE             g_hinst;    // application instance
HWND                  g_hwndMain; // application window
*/
LPDIRECTINPUT7        g_lpDI; 
LPDIRECTINPUTDEVICE7  g_lpDIDevice; 
 
BOOL WINAPI DI_Init() 
{ 
    HRESULT hr; 
 
    // Create the DirectInput object. 
    hr = DirectInputCreateEx(g_hinst, DIRECTINPUT_VERSION, 
                           IID_IDirectInput7, (void**)&g_lpDI, NULL); 
    if FAILED(hr) return FALSE; 
 
    // Retrieve a pointer to an IDirectInputDevice7 interface 
    hr = g_lpDI->CreateDeviceEx(GUID_SysKeyboard, 
            IID_IDirectInputDevice7, (void**)&g_lpDIDevice, NULL); 
    if FAILED(hr) 
    { 
        DI_Term(); 
        return FALSE; 
    } 
 
// Now that you have an IDirectInputDevice7 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; 
}