DIEX3.CPP
上传用户:bangxh
上传日期:2007-01-31
资源大小:42235k
文件大小:14k
源码类别:

Windows编程

开发平台:

Visual C++

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