views:

622

answers:

2

Consider that, for a Windows video game, I need to determine if the key which generates the ` and ~ characters on the U.S. English keyboard layout (which is usually below the Escape key and left to 1) has been pressed. This may sound like a trivial question, but it doesn't seem like one to me.

When Windows sends keyboard messages, it specifies the virtual key code and the OEM scan code. We can't rely on the OEM scan code, because "the value depends on the OEM" - and nor can we depend on the virtual key code, because it depends on the currently active keyboard layout.

Our current "solution" is to use LoadKeyboardLayout and MapVirtualKeyEx to find the OEM scan code of the key that generates the ` character on the U.S. English keyboard layout, then just listen for that OEM scan code. The problem is that this doesn't work if the user doesn't have the U.S. English layout installed.

Is there a real way to do this on Windows?

+2  A: 

The OEM scancode does not change from keyboard to keyboard. No reason not to use it.

Back in the DOS-days the same scancodes have been used for games because it has been the only way to detect key-up and key-down events. Noone had problems with it and I doubt it will change in the future.

If you want another option you may want to give DirectInput-API a try. It gives you the raw scancodes as well and if I'm not mistaken you can also query the physical position, dimension and whatnot of each key.

Nils Pipenbrinck
Thanks. Do you have, by any chance, a source for the statement in your first paragraph?
CyberShadow
Unfortunately I don't have any source, but the scancode mapping hasn't changed since the IBM XT (it has been extended for the 102 key keyboards though). With USB-Keyboards the scan-codes are emulated in the driver anyways.
Nils Pipenbrinck
A: 

Tie the game action to the character, not the position of the key. Otherwise, how do you tell the user which key to press? "under the escape key"? They may not have anything there, but if you tell them "the ^ key", they can look for it.

You'll probably also want to make it configurable to accomodate exotic keyboard layouts and user preferences.

Michael Borgwardt
Sorry, but we need to use the key by its position, not by the character it generates. The reason for this is because of its position relative to other keys which aren't layout-dependant (e.g. the number keys, but in our case the F1..F12 keys). And yes, the docs simply state "the key under ESC".
CyberShadow