Reputation: 51
I've read everywhere that using windows messages is preferable to DirectInput. Despite this, there are many DirectInput tutorials and barely any for dealing with keyboard in Windows messaging. After not finding any good sources, I began to try it on my own.
I made two 256 member bool arrays to hold if keys were pressed. I want to make it so that I can look at m_bKeyDown[256] to see if a key was pressed this frame, and m_bKeyDown to see if it is being held down, but not pressed this frame. My MsgProc switch statement is as follows:
LRESULT D3DApp::MsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){
switch(msg){
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_KEYDOWN:
if(m_bKeyPressed[wParam])
m_bKeyDown[wParam] = false;
else
m_bKeyDown[wParam] = true;
break;
m_bKeyPressed[wParam] = true;
case WM_KEYUP:
m_bKeyDown[wParam] = false;
m_bKeyPressed[wParam] = false;
break;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
I tested it by having it make a sound when I held down the F1 key. Ideally the sound should not repeat until I release the button and press it again:
if(m_bKeyDown[VK_F1])
m_fMod.FPlaySound(testSound);
There seems to be no difference though, the sound repeats when I hold down the button. How do I fix the loop or set up Windows messaging to do this? Am I on the right track or should I go a completely different direction?
Edit: I used iedoc's below example and now it does better, but the sound still plays three times before stopping, like there is a delay for some reason. Any idea how to avoid this?
Upvotes: 0
Views: 1824
Reputation: 2324
try this:
LRESULT D3DApp::MsgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){
switch(msg){
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_KEYDOWN:
if(!m_bKeyPressed[wParam])
{
m_bKeyDown[wParam] = true;
m_bKeyPressed[wParam] = true;
}
else
m_bKeyDown[wParam] = false;
break;
case WM_KEYUP:
m_bKeyDown[wParam] = false;
m_bKeyPressed[wParam] = false;
break;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
Upvotes: 1