home *** CD-ROM | disk | FTP | other *** search
/ Tricks of the Windows Gam…ming Gurus (2nd Edition) / Disc2.iso / msdn_vcb / samples / vc98 / sdk / graphics / directx / diex3 / diex3.cpp next >
C/C++ Source or Header  |  1997-07-14  |  14KB  |  520 lines

  1. /**************************************************************************
  2.  
  3.     DIEX3.CPP - DirectInput simple sample 3
  4.  
  5.     Demonstrates an application which receives keyboard data
  6.     in non-exclusive mode via a game loop.
  7.  
  8.  **************************************************************************/
  9. /**************************************************************************
  10.  
  11.     (C) Copyright 1997 Microsoft Corp.  All rights reserved.
  12.  
  13.     You have a royalty-free right to use, modify, reproduce and
  14.     distribute the Sample Files (and/or any modified version) in
  15.     any way you find useful, provided that you agree that
  16.     Microsoft has no warranty obligations or liability for any
  17.     Sample Application Files which are modified.
  18.  
  19.  **************************************************************************/
  20.  
  21. #include <windows.h>
  22. #include <dinput.h>
  23.  
  24. #include "diex3.h"
  25.  
  26. /****************************************************************************
  27.  *
  28.  *      Global variables
  29.  *
  30.  ****************************************************************************/
  31.  
  32. char c_szClassName[] = "DIEX3";
  33.  
  34. HINSTANCE       g_hinst;                /* My instance handle */
  35. BOOL            g_fPaused = TRUE;       /* Should I be paused? */
  36.  
  37. /****************************************************************************
  38.  *
  39.  *      DirectInput globals
  40.  *
  41.  ****************************************************************************/
  42.  
  43. LPDIRECTINPUT           g_pdi;
  44. LPDIRECTINPUTDEVICE     g_pKeyboard;
  45. char                    g_szText[1024]; /* What we display in client area */
  46.  
  47. /****************************************************************************
  48.  *
  49.  *      Complain
  50.  *
  51.  *      Whine and moan.
  52.  *
  53.  ****************************************************************************/
  54.  
  55. void
  56. Complain(
  57.     HWND hwndOwner,
  58.     HRESULT hr,
  59.     LPCSTR pszMessage
  60. )
  61. {
  62.     MessageBox(hwndOwner, pszMessage, "DirectInput Sample", MB_OK);
  63. }
  64.  
  65. /****************************************************************************
  66.  *
  67.  *      DIInit
  68.  *
  69.  *      Initialize the DirectInput variables.
  70.  *
  71.  *      This entails the following four functions:
  72.  *
  73.  *          DirectInputCreate
  74.  *          IDirectInput::CreateDevice
  75.  *          IDirectInputDevice::SetDataFormat
  76.  *          IDirectInputDevice::SetCooperativeLevel
  77.  *
  78.  ****************************************************************************/
  79.  
  80. BOOL
  81. DIInit(
  82.     HWND hwnd
  83. )
  84. {
  85.     HRESULT hr;
  86.  
  87.     /*
  88.      *  Register with the DirectInput subsystem and get a pointer
  89.      *  to a IDirectInput interface we can use.
  90.      *
  91.      *  Parameters:
  92.      *
  93.      *      g_hinst
  94.      *
  95.      *          Instance handle to our application or DLL.
  96.      *
  97.      *      DIRECTINPUT_VERSION
  98.      *
  99.      *          The version of DirectInput we were designed for.
  100.      *          We take the value from the <dinput.h> header file.
  101.      *
  102.      *      &g_pdi
  103.      *
  104.      *          Receives pointer to the IDirectInput interface
  105.      *          that was created.
  106.      *
  107.      *      NULL
  108.      *
  109.      *          We do not use OLE aggregation, so this parameter
  110.      *          must be NULL.
  111.      *
  112.      */
  113.     hr = DirectInputCreate(g_hinst, DIRECTINPUT_VERSION, &g_pdi, NULL);
  114.  
  115.     if (FAILED(hr)) {
  116.         Complain(hwnd, hr, "DirectInputCreate");
  117.         return FALSE;
  118.     }
  119.  
  120.     /*
  121.      *  Obtain an interface to the system keyboard device.
  122.      *
  123.      *  Parameters:
  124.      *
  125.      *      GUID_SysKeyboard
  126.      *
  127.      *          The instance GUID for the device we wish to access.
  128.      *          GUID_SysKeyboard is a predefined instance GUID that
  129.      *          always refers to the system keyboard device.
  130.      *
  131.      *      &g_pKeyboard
  132.      *
  133.      *          Receives pointer to the IDirectInputDevice interface
  134.      *          that was created.
  135.      *
  136.      *      NULL
  137.      *
  138.      *          We do not use OLE aggregation, so this parameter
  139.      *          must be NULL.
  140.      *
  141.      */
  142.     hr = g_pdi->CreateDevice(GUID_SysKeyboard, &g_pKeyboard, NULL);
  143.  
  144.     if (FAILED(hr)) {
  145.         Complain(hwnd, hr, "CreateDevice");
  146.         return FALSE;
  147.     }
  148.  
  149.     /*
  150.      *  Set the data format to "keyboard format".
  151.      *
  152.      *  A data format specifies which controls on a device we
  153.      *  are interested in, and how they should be reported.
  154.      *
  155.      *  This tells DirectInput that we will be passing an array
  156.      *  of 256 bytes to IDirectInputDevice::GetDeviceState.
  157.      *
  158.      *  Parameters:
  159.      *
  160.      *      c_dfDIKeyboard
  161.      *
  162.      *          Predefined data format which describes
  163.      *          an array of 256 bytes, one per scancode.
  164.      */
  165.     hr = g_pKeyboard->SetDataFormat(&c_dfDIKeyboard);
  166.  
  167.     if (FAILED(hr)) {
  168.         Complain(hwnd, hr, "SetDataFormat");
  169.         return FALSE;
  170.     }
  171.  
  172.  
  173.     /*
  174.      *  Set the cooperativity level to let DirectInput know how
  175.      *  this device should interact with the system and with other
  176.      *  DirectInput applications.
  177.      *
  178.      *  Parameters:
  179.      *
  180.      *      DISCL_NONEXCLUSIVE
  181.      *
  182.      *          Retrieve keyboard data when acquired, not interfering
  183.      *          with any other applications which are reading keyboard
  184.      *          data.
  185.      *
  186.      *      DISCL_FOREGROUND
  187.      *
  188.      *          If the user switches away from our application,
  189.      *          automatically release the keyboard back to the system.
  190.      *
  191.      */
  192.     hr = g_pKeyboard->SetCooperativeLevel(hwnd,
  193.                                        DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
  194.  
  195.     if (FAILED(hr)) {
  196.         Complain(hwnd, hr, "SetCooperativeLevel");
  197.         return FALSE;
  198.     }
  199.  
  200.     return TRUE;
  201.  
  202. }
  203.  
  204. /****************************************************************************
  205.  *
  206.  *      DITerm
  207.  *
  208.  *      Terminate our usage of DirectInput.
  209.  *
  210.  ****************************************************************************/
  211.  
  212. void
  213. DITerm(void)
  214. {
  215.  
  216.     /*
  217.      *  Destroy any lingering IDirectInputDevice object.
  218.      */
  219.     if (g_pKeyboard) {
  220.  
  221.         /*
  222.          *  Cleanliness is next to godliness.  Unacquire the device
  223.          *  one last time just in case we got really confused and tried
  224.          *  to exit while the device is still acquired.
  225.          */
  226.         g_pKeyboard->Unacquire();
  227.  
  228.         g_pKeyboard->Release();
  229.         g_pKeyboard = NULL;
  230.     }
  231.  
  232.     /*
  233.      *  Destroy any lingering IDirectInput object.
  234.      */
  235.     if (g_pdi) {
  236.         g_pdi->Release();
  237.         g_pdi = NULL;
  238.     }
  239.  
  240. }
  241.  
  242. /****************************************************************************
  243.  *
  244.  *      Ex_OnPaint
  245.  *
  246.  *      Display the current keyboard state.
  247.  *
  248.  ****************************************************************************/
  249.  
  250. LRESULT
  251. Ex_OnPaint(
  252.     HWND hwnd
  253. )
  254. {
  255.     PAINTSTRUCT ps;
  256.     HDC hdc = BeginPaint(hwnd, &ps);
  257.  
  258.     if (hdc) {
  259.  
  260.         ExtTextOut(hdc, 0, 0, ETO_OPAQUE, &ps.rcPaint, g_szText,
  261.                    lstrlen(g_szText), NULL);
  262.  
  263.         EndPaint(hwnd, &ps);
  264.     }
  265.  
  266.     return 0;
  267. }
  268.  
  269. /****************************************************************************
  270.  *
  271.  *      Ex_OneFrame
  272.  *
  273.  *      The game plays here.
  274.  *
  275.  *      Our "game" consists entirely of reading keyboard data
  276.  *      and displaying it.
  277.  *
  278.  ****************************************************************************/
  279.  
  280. void
  281. Ex_OneFrame(HWND hwnd)
  282. {
  283.  
  284.     if (g_pKeyboard) {
  285.  
  286.         BYTE diks[256];             /* DirectInput keyboard state buffer */
  287.         HRESULT hr;
  288.  
  289.     again:;
  290.         hr = g_pKeyboard->GetDeviceState(sizeof(diks), &diks);
  291.         if (hr == DIERR_INPUTLOST) {
  292.             /*
  293.              *  DirectInput is telling us that the input stream has
  294.              *  been interrupted.  We aren't tracking any state
  295.              *  between polls, so we don't have any special reset
  296.              *  that needs to be done.  We just re-acquire and
  297.              *  try again.
  298.              */
  299.             hr = g_pKeyboard->Acquire();
  300.             if (SUCCEEDED(hr)) {
  301.                 goto again;
  302.             }
  303.         }
  304.  
  305.         if (SUCCEEDED(hr)) {
  306.             char szBuf[1024];
  307.  
  308.             /*
  309.              *  Build the new status string.
  310.              *
  311.              *  Display the scan codes of the keys that are down.
  312.              */
  313.             int i;
  314.             char *psz = szBuf;
  315.             for (i = 0; i < 256; i++) {
  316.                 if (diks[i] & 0x80) {
  317.                     psz += wsprintf(psz, "%02x ", i);
  318.                 }
  319.             }
  320.             *psz = 0;                   /* Terminate the string */
  321.  
  322.             /*
  323.              *  Trigger a repaint only if the status string changed.
  324.              *  This avoids flicker.
  325.              */
  326.             if (lstrcmp(g_szText, szBuf)) {
  327.                 lstrcpy(g_szText, szBuf);
  328.                 InvalidateRect(hwnd, NULL, TRUE);
  329.             }
  330.         }
  331.     }
  332.  
  333.     /*
  334.      *  Sleep for a few milliseconds to simulate a 30fps frame rate.
  335.      */
  336.     Sleep(1000 / 30);
  337.  
  338. }
  339.  
  340. /****************************************************************************
  341.  *
  342.  *      Ex_SyncAcquire
  343.  *
  344.  *      Acquire or unacquire the keyboard, depending on the the g_fPaused
  345.  *      flag.  This synchronizes the device with our internal view of
  346.  *      the world.
  347.  *
  348.  ****************************************************************************/
  349.  
  350. void
  351. Ex_SyncAcquire(HWND hwnd)
  352. {
  353.     if (g_fPaused) {
  354.         if (g_pKeyboard) g_pKeyboard->Unacquire();
  355.     } else {
  356.         if (g_pKeyboard) g_pKeyboard->Acquire();
  357.     }
  358. }
  359.  
  360. /****************************************************************************
  361.  *
  362.  *      Ex_WndProc
  363.  *
  364.  *      Window procedure for simple sample.
  365.  *
  366.  ****************************************************************************/
  367.  
  368. LRESULT CALLBACK
  369. Ex_WndProc(
  370.     HWND hwnd,
  371.     UINT msg,
  372.     WPARAM wParam,
  373.     LPARAM lParam
  374. )
  375. {
  376.  
  377.     switch (msg) {
  378.  
  379.     case WM_PAINT:      return Ex_OnPaint(hwnd);
  380.  
  381.     /*
  382.      *  WM_ACTIVATE
  383.      *
  384.      *      Windows sends this message when the window becomes
  385.      *      the active window or stops being the active window.
  386.      *
  387.      *      wParam = WA_INACTIVE if window is no longer active
  388.      *
  389.      *      wParam = WA_ACTIVE or WA_CLICKACTIVE if window is now active
  390.      *
  391.      *      If we are losing activation, then pause.
  392.      *
  393.      *      If we are gaining activation, then unpause.
  394.      *
  395.      *      After deciding whether we are paused or unpaused,
  396.      *      tell DirectInput that we don't (paused) or do (unpaused)
  397.      *      want non-exclusive access to the keyboard.
  398.      *
  399.      */
  400.     case WM_ACTIVATE:
  401.         g_fPaused = wParam == WA_INACTIVE;
  402.         Ex_SyncAcquire(hwnd);
  403.         break;
  404.  
  405.     case WM_DESTROY:
  406.         PostQuitMessage(0);
  407.         break;
  408.  
  409.     }
  410.  
  411.     return DefWindowProc(hwnd, msg, wParam, lParam);
  412. }
  413.  
  414. /****************************************************************************
  415.  *
  416.  *      AppInit
  417.  *
  418.  *      Set up everything the application needs to get started.
  419.  *
  420.  ****************************************************************************/
  421.  
  422. HWND
  423. AppInit(
  424.     HINSTANCE hinst,
  425.     int nCmdShow
  426. )
  427. {
  428.  
  429.     /*
  430.      *  Save instance handle for future reference.
  431.      */
  432.     g_hinst = hinst;
  433.  
  434.     /*
  435.      *  Set up the window class.
  436.      */
  437.     WNDCLASS wc;
  438.  
  439.     wc.hCursor        = LoadCursor(0, IDC_ARROW);
  440.     wc.hIcon          = LoadIcon(NULL, MAKEINTRESOURCE(IDI_APPLICATION));
  441.     wc.lpszMenuName   = NULL;
  442.     wc.lpszClassName  = c_szClassName;
  443.     wc.hbrBackground  = 0;
  444.     wc.hInstance      = hinst;
  445.     wc.style          = 0;
  446.     wc.lpfnWndProc    = Ex_WndProc;
  447.     wc.cbClsExtra     = 0;
  448.     wc.cbWndExtra     = 0;
  449.  
  450.     if (!RegisterClass(&wc)) {
  451.         return NULL;
  452.     }
  453.  
  454.     HWND hwnd = CreateWindow(
  455.                     c_szClassName,                  // Class name
  456.                     "DIEX3 - Alt+F4 to exit",       // Caption
  457.                     WS_OVERLAPPEDWINDOW,            // Style
  458.                     CW_USEDEFAULT, CW_USEDEFAULT,   // Position
  459.                     CW_USEDEFAULT, CW_USEDEFAULT,   // Size
  460.                     NULL,                           // No parent
  461.                     NULL,                           // No menu
  462.                     g_hinst,                        // inst handle
  463.                     0                               // no params
  464.                     );
  465.  
  466.     if (!DIInit(hwnd)) {
  467.         DestroyWindow(hwnd);
  468.         return NULL;
  469.     }
  470.  
  471.     ShowWindow(hwnd, nCmdShow);
  472.  
  473.     return hwnd;
  474. }
  475.  
  476. /****************************************************************************
  477.  *
  478.  *      WinMain
  479.  *
  480.  *      Application entry point.
  481.  *
  482.  ****************************************************************************/
  483.  
  484. int PASCAL
  485. WinMain(HINSTANCE hinst, HINSTANCE hinstPrev, LPSTR szCmdLine, int nCmdShow)
  486. {
  487.     MSG msg;
  488.     msg.wParam = 0;         /* In case something goes horribly wrong */
  489.  
  490.     HWND hwnd = AppInit(hinst, nCmdShow);
  491.  
  492.     if (hwnd) {
  493.  
  494.         /*
  495.          *  Standard game loop.
  496.          */
  497.         for (;;) {
  498.             if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
  499.  
  500.                 /* If it's a quit message, we're outta here */
  501.                 if (msg.message == WM_QUIT) {
  502.                     break;
  503.                 } else {
  504.                     TranslateMessage(&msg);
  505.                     DispatchMessage(&msg);
  506.                 }
  507.             } else if (g_fPaused) {
  508.                 WaitMessage();
  509.             } else {
  510.                 Ex_OneFrame(hwnd);
  511.             }
  512.         }
  513.     }
  514.  
  515.     DITerm();
  516.  
  517.     return msg.wParam;
  518.  
  519. }
  520.