?/TD>
Microsoft DirectX 9.0

Step 6: Retrieving Data from the Joystick


Because your application is more likely concerned with the position of the joystick axes than with their movement, you probably want to retrieve immediate rather than buffered data from the device. You can do this by polling with IDirectInputDevice8::GetDeviceState. Note that not all device drivers notify Microsoft?DirectInput?when the state of the device changes. Therefore, it is always good policy to call the IDirectInputDevice8::Poll method before checking the device state.

The Joystick application calls the following function from the Microsoft Windows?message loop.

HRESULT UpdateInputState(HWND hDlg)
{
    HRESULT     hr;
    CHAR        strText[128]; // Device state text
    DIJOYSTATE2 js;           // Direct Input joystick state 
    CHAR*       str;

    if (NULL == g_pJoystick) 
        return S_OK;

    // Poll the device to read the current state
    hr = g_pJoystick->Poll(); 
    if (FAILED(hr))  
    {
        // Attempt to reacquire joystick
    }
    hr = g_pJoystick->GetDeviceState(sizeof(DIJOYSTATE2), &js);
    if (FAILED(hr))
        return hr; 

Note the call to IDirectInputDevice8::GetDeviceState. The first parameter is the size of the structure in which the data is returned, and the second parameter is the address of this structure, which is of type DIJOYSTATE2. This structure holds data for up to six axes, 128 buttons, and four point-of-view hats. The sample program proceeds to view the state of all axes and buttons, and one slider. This information is then displayed in the main dialog window.

Joystick buttons work just like keys or mouse buttons. If the high bit of the returned byte is 1, the button is pressed.

For additional DirectInput tutorials, see DirectInput C/C++ Tutorials.



© 2002 Microsoft Corporation. All rights reserved.