Hello :)

I'm making a very simple game in C++ (very much like the old DOS game Supaplex if anybody know that :P). I'm using the windows API, not GDI, DirectX or anything like that. I've only just begun learning the Win Api some days ago :)

I have the problem that I don't know how to check if multiple keys are pressed. I want to have that only when holding down the space key, you can do something with the arrow keys. I had tried to search the web, but I could only find something about using shift and ctrl as hotkeys. Someone know how to do this?

Dani AI

Generated

As suggested, handling WM_KEYDOWN and WM_KEYUP is the right starting point. For a game you want a persistent, pollable keyboard state rather than doing logic only inside the message handler. A simple, reliable pattern is to keep a 256-entry boolean key array updated by WndProc and then read that array each frame in the game loop. That lets you test combinations (for example, do arrow-key moves only while VK_SPACE is held) and also lets you detect the transition from "not pressed" to "pressed" if you need one-shot actions.

// global
static bool keys[256] = { false };

// in WndProc:
case WM_KEYDOWN:
    keys[wParam & 0xFF] = true;
    break;
case WM_KEYUP:
    keys[wParam & 0xFF] = false;
    break;

// in your game update:
if (keys[VK_SPACE]) {
    if (keys[VK_LEFT])  { /* move left */ }
    if (keys[VK_RIGHT]) { /* move right */ }
}

Tips and caveats: pump messages inside your main loop (PeekMessage/TranslateMessage/DispatchMessage) so WM_KEYUP arrives; otherwise keys can appear stuck. WM_KEYDOWN will auto-repeat while held—if you need only the first press, check the previous array value before setting it or inspect the lParam repeat flag. If you prefer polling, GetAsyncKeyState is an alternative. See the Microsoft docs for details on WM_KEYDOWN and GetAsyncKeyState.

Recommended Answers

All 2 Replies

In short, you probably want to detect the WM_KEYDOWN message from the spacebar, and until you see the WM_KEYUP from spacebar, process other key messages.

hehe thx for the fast reply, why didn't I think of that? :P

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.