Loading

Win32: Responding to Key Presses

Responding to Key Presses

In this Win32 C++ video tutorial, we demonstrate how to handle and respond to simple key press events. The video gives demonstrations of three types of events: WM_KEYDOWN, WM_CHAR, and WM_KEYUP. The WM_KEYDOWN event is sent every time that a key is pressed on the keyboard, including non-character keys like insert, delete, and the arrow keys.

The arrow keys are particularly useful for directional controls in making simple games. These four directional keys are located at the lower right of the keyboard.

case WM_KEYDOWN:
{
    switch (wParam) {
        case VK_LEFT:
        {
            ::MessageBox(hWnd, _T("Left Arrow") , _T("Key Pressed"), MB_OK);
            break;
        }
        case 'X':
        {
            ::MessageBox(hWnd, _T("X") , _T("Key Pressed"), MB_OK);
            break;
        }
    }
    break;
}

Above, we have code to handle key press events for the left arrow key and the "X" key. The key value for the left arrow is VK_LEFT, which stands for "virtual key" since this is a virtual key code. For "X", we need to use the ASCII character code for the uppercase letter, which we get by putting the uppercase "X" in single quotes. However, WM_KEYDOWN character key events are triggered for both upper and lower case letters. To add this event handler, put the case statement in the switch statement inside of the WndProc() function.

case WM_CHAR:
{
    switch (wParam) {
        case _T('a'):
        {
            ::MessageBox(hWnd, _T("a") , _T("Key Pressed"), MB_OK);
            break;
        }
        case _T('A'):
        {
            ::MessageBox(hWnd, _T("A") , _T("Key Pressed"), MB_OK);
            break;
        }
    }
    break;
}

The WM_KEYDOWN event does not distinguish between upper and lower case character messages. To do this, you should use a WM_CHAR message handler like the one shown above. This code will pop up a different message box, depending on whether an upper or lower case "a" is pressed. To add this handler, put it in the switch statement in the WndProc() function as well.

case WM_KEYUP:
{
    switch (wParam) {
        case VK_UP:
        {
            ::MessageBox(hWnd, _T("Up Arrow") , _T("Key Released"), MB_OK);
            break;
        }
    }
    break;
}

In order to determine how long a key is pressed, we need to catch both the WM_KEYDOWN event and the WM_KEYUP event for that particular key. It is often useful to do this. So, we have given an example of a WM_KEYUP handler above. This handler pops up a message box when the up arrow key is released.

In up-coming lessons, we will make use of key events for controls in video games. For example, we might use arrow key controls to move around a spaceship and the "f" key for firing.