Win32 WM_KEYDOWN和WM_KEYUP以及状态变得越来越困难"

时间:2016-09-13 08:04:38

标签: c++ winapi

下面是我用来捕获按键是什么的代码,我根据状态更新按键的状态。 我将雕像保存在我的简单数组0,1,2,3中。 格式为:keyboardmap [256] = {0};

问题是,无论我做什么,键都会在某些时候卡住。它们永远不会重置为零,就像WM_KEYUP无法正常启动一样。

  while (true)
  {

    if ( PeekMessage(&msg, 0, 0, 0, PM_REMOVE) )
    {
      TranslateMessage(&msg);
      DispatchMessage(&msg);

      if (msg.message == WM_QUIT)
      {
        break;
      }

      // Check for keystates and update them.
      if (msg.message == WM_KEYDOWN)
      {
        // Fetch the key state.
        unsigned int keycode = msg.wParam;
        unsigned int cstate = engine.GetKeyState(msg.wParam);

        if (engine.GetKeyState(keycode) == 0)
        {
          engine.SetKeyState(keycode, 1); // Just started pressing.
        }
        else
        {
          engine.SetKeyState(keycode, 2); // Actively pressed down.
        }
      }
      else if (msg.message == WM_KEYUP)
      {
        // Fetch the key state.
        unsigned int keycode = msg.wParam;
        unsigned int cstate = engine.GetKeyState(msg.wParam);

        if ( engine.GetKeyState(keycode) == 2)
        {
          engine.SetKeyState(keycode, 3);
        }
        else
        {
          engine.SetKeyState(keycode, 0);
        }
      }
    }
  }

1 个答案:

答案 0 :(得分:1)

这不是消息循环应该如何。将以下示例用于需要不断更新游戏/屏幕的游戏引擎:

in.readTypedList(images, SingleImage.CREATOR);

窗口的消息应该在单独的窗口过程中处理:

WNDCLASSEX wc = { sizeof(WNDCLASSEX) };
wc.lpfnWndProc = WndProc;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = L"WindowClass";
RegisterClassEx(&wc);

CreateWindow(...);

MSG msg = { 0 };
//while (msg.message != WM_QUIT) <=== removed in edit
while(true)  //<=== **** edit **** 
{
    if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    {
        if(msg.message == WM_QUIT) //<=== **** edit **** 
            break;
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    else
    {
        engine.update();
    }
}