Win32 Tutorials


Keyboard Input

Tutorials > Win32 > Keyboard Input

View Full Source


This tutorial will explain how to retrieve keyboard input from windows messages. This is done by receiving the WM_KEYUP and WM_KEYDOWN messages.

Contents of main.cpp :

The first we will discuss is the WM_KEYDOWN message. If you look at the wParam parameter, it will give you the key that was pressed. To check for a letter, you can simply compare the wParam to the character as shown below. A message box is displayed if the T key is pressed.

	case WM_KEYDOWN :
		if (wParam == 'T')
			MessageBox(hwnd, "T Pressed", "T", MB_OK);

Special keys can be checked by using their identifiers. These identifiers start with VK_* eg. VK_ESCAPE, VK_SHIFT, VK_CONTROL, VK_UP, VK_NUMPADX, VK_F1, etc.

Below, we simply send a close message if the escape key is pressed. You can send any message yourself to a window by using the SendMessage function. The function takes 4 parameters which are the same as the WndProc parameters.

The first parameter is the handle to the window you want to send the message to. The second parameter is what message you want to send. The third and fourth parameters are the WPARAM and LPARAM parameters which allow you to pass extra information onto the WndProc function. The WM_CLOSE message does not require any extra information so we can therefore pass 0 for both of these parameters.

		else if (wParam == VK_ESCAPE)
			SendMessage(hwnd, WM_CLOSE, 0, 0);

The WM_KEYUP message works in the same way as WM_KEYDOWN except that this message is sent when you lift your finger from the key.

	case WM_KEYUP :
		if (wParam == 'R')
			MessageBox(hwnd, "R Pressed", "R", MB_OK);

If you run the program, you can press the T key. As soon as you press the key, a message box will be displayed. Next, try to hold in the R key and then release it. A message box will appear after releasing the key.

You should now be able to process keystrokes passed onto your window. The next tutorial will deal with mouse input.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++

< Tutorial 06 - Message Loop Tutorial 08 - Mouse Input >

Back to Top

All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer