PDA

Click to See Complete Forum and Search --> : Detecting keypress


Dec 9th, 2000, 04:00 PM
In a window, how do i detect if an arrow key has been pressed?

HarryW
Dec 9th, 2000, 08:50 PM
You can either use GetAsynchKeyState to test for it, or (I think) you can trap it in your WindowProc as an event. Probably WM_KEYDOWN or something like that. I'm not too sure about that one.

*Looks in MSDN*

Here it is, WM_KEYDOWN:

WM_KEYDOWN
The WM_KEYDOWN message is posted to the window with the
keyboard focus when a nonsystem key is pressed. A nonsystem
key is a key that is pressed when the alt key is not
pressed.

WM_KEYDOWN
nVirtKey = (int) wParam; // virtual-key code
lKeyData = lParam; // key data

Parameters
nVirtKey
Value of wParam. Specifies the virtual-key code of the
nonsystem key.
lKeyData
Value of lParam. Specifies the repeat count, scan code,
extended-key flag, context code, previous key-state flag,
and transition-state flag, as shown in the following
table.
Value Description
0–15 Specifies the repeat count for the current
message. The value is the number of times the
keystroke is auto-repeated as a result of the user
holding down the key. If the keystroke is held long
enough, multiple messages are sent. However, the
repeat count is not cumulative.
16–23 Specifies the scan code. The value depends on the
original equipment manufacturer (OEM).
24 Specifies whether the key is an extended key, such
as the right-hand alt and ctrl keys that appear on
an enhanced 101- or 102-key keyboard. The value is
1 if it is an extended key; otherwise, it is 0.
25–28 Reserved; do not use.
29 Specifies the context code. The value is always 0
for a WM_KEYDOWN message.
30 Specifies the previous key state. The value is 1 if
the key is down before the message is sent, or it
is 0 if the key is up.
31 Specifies the transition state. The value is always
0 for a WM_KEYDOWN message.


Return Values
An application should return zero if it processes this message.

HarryW
Dec 9th, 2000, 08:57 PM
Oh yes, and GetAsynchkeystate:

It's easiest if you define a macro or two which you can then use. Here they are, you don't really need both but you might want them:


#define KEYDOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
#define KEYUP(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 0 : 1)


You can then use them like this:


if (KEYDOWN(VK_ESCAPE))
SendMessage(main_window_handle,WM_CLOSE,0,0);