Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a certain key is pressed, knowing only its position on U.S. keyboards?

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?

like image 646
Vladimir Panteleev Avatar asked Jan 26 '26 02:01

Vladimir Panteleev


1 Answers

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.

like image 199
Nils Pipenbrinck Avatar answered Jan 27 '26 16:01

Nils Pipenbrinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!