Using Joystick Messages

The remainder of this chapter presents code fragments from a simple joystick game that performs the useful function of shooting holes in the desktop: it gets position and button-state information from the joystick services and, when a user presses the joystick buttons, plays waveform resources and paints bullet holes on the screen.

Most of the joystick-control code is in the main window function. In the following WM_CREATE case of the message handler, the application captures input from joystick 1:

case WM_CREATE:
    if(joySetCapture(hWnd, JOYSTICKID1,  NULL, FALSE))
    {
        MessageBeep(MB_ICONEXCLAMATION);
        MessageBox(hWnd, "Couldn't capture the joystick.", NULL,
                        MB_OK | MB_ICONEXCLAMATION);
        PostMessage(hWnd,WM_CLOSE,0,0L);
    }
    break;

In response to the MM_JOY1MOVE messages, the application changes the position of the cursor and, if either button is pressed, draws a hole in the desktop:

case MM_JOY1MOVE :
    if(wParam & (JOY_BUTTON1 | JOY_BUTTON2))
        DrawFire(hWnd);
    DrawSight(lParam);                     // Calculate new cursor position
    break;

In response to the MM_JOY1BUTTONDOWN messages, the application uses sndPlaySound to play a waveform audio file:

case MM_JOY1BUTTONDOWN :
    if(wParam & JOY_BUTTON1)
    {
        sndPlaySound(lpButton1, SND_LOOP | SND_ASYNC | SND_MEMORY);
        DrawFire(hWnd);
    }
    else if(wParam & JOY_BUTTON2)
    {
        sndPlaySound(lpButton2, SND_ASYNC | SND_MEMORY |  SND_LOOP);
        DrawFire(hWnd);
    }
    break;

By specifying the SND_LOOP and SND_ASYNC flags with sndPlaySound, the JOYTOY application repeats the waveform playback until the button is released.

When a button is released, the window function receives a MM_JOY1BUTTONUP message, which it handles as follows:

case MM_JOY1BUTTONUP :
    sndPlaySound(NULL, 0);
    break; 

This sequence stops the waveform-audio playback.