Better Way to programmatically detect a key press?

后端 未结 1 846
陌清茗
陌清茗 2021-01-24 20:43

I\'m currently using this:

while (1)
    {
        if (GetAsyncKeyState(VK_F1))
        {
        //do something
        }
    }

to detect if a

相关标签:
1条回答
  • 2021-01-24 21:16

    The better way of doing this is using your WndProc(). So use standard WM_KEYDOWN/WM_KEYUP messages to handle keyboard input. Here is an example:

    LRESULT CALLBACK WndProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
    {
      switch ( uMsg )
      {
        case WM_CLOSE:
            DestroyWindow(hwnd);
        break;
        case WM_DESTROY:
            PostQuitMessage(0);
        break;
          case WM_KEYDOWN:
          if ( wParam == VK_F1 )
          {
            // Do something here
            return 0L;
          }
          break;
      }
    
      return DefWindowProc( hwnd, uMsg, wParam, lParam );
    }
    
    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
        LPSTR lpCmdLine, int nCmdShow)
    {
        WNDCLASSEX wc;
        HWND hwnd;
        MSG Msg;
    
        //Step 1: Registering the Window Class
        wc.cbSize        = sizeof(WNDCLASSEX);
        wc.style         = 0;
        wc.lpfnWndProc   = WndProc;
        // lots of other attrs ...
        wc.lpszClassName = g_szClassName;
        wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);
    
        if(!RegisterClassEx(&wc))
            return 0;
    
        // Step 2: Creating the Window
        hwnd = CreateWindowEx(
            ...
            g_szClassName,
            ...);
    
        if(hwnd == NULL)
             return 0;
    
        ShowWindow(hwnd, nCmdShow);
        UpdateWindow(hwnd);
    
        // Step 3: The Message Loop
        while(GetMessage(&Msg, NULL, 0, 0) > 0)
        {
            TranslateMessage(&Msg);
            DispatchMessage(&Msg);
        }
        return Msg.wParam;
    }
    
    0 讨论(0)
提交回复
热议问题