Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows virtual key codes

How can I implement a function like std::string VirtualKeyCodeToStdString(UCHAR key) which returns virtual keys descriptions?

Example: input is VK_CAPITAL, return value is std::string("Caps Lock")

like image 929
Inline Avatar asked Jun 29 '16 13:06

Inline


People also ask

What are virtual key codes?

Virtual keys mainly consist of actual keyboard keys, but also include "virtual" elements such as the three mouse buttons. The virtual keys also include many "keys" which usually do not exist at all. A key's virtual-key code does not change when modifier keys (Ctrl, Alt, Shift, etc.)


1 Answers

A simple way to convert the VK code to a text representation of the key is to:

  1. Use MapVirtualKey to convert the VK code to a scan code.
  2. Do a bit shift to convert that value into a long where bits 16-23 are the scan code
  3. Use GetKeyNameText to obtain the name of the key.

For example:

WCHAR name[1024];
UINT scanCode = MapVirtualKeyW(VK_CAPITAL, MAPVK_VK_TO_VSC);
LONG lParamValue = (scanCode << 16);
int result = GetKeyNameTextW(lParamValue, name, 1024);
if (result > 0)
{
    std::wcout << name << endl; // Output: Caps Lock
}

If you're doing this in response to a WM_KEYDOWN or other message that passes the scan code in the LPARAM you can skip the first two steps, since those are just there to massage the VK code into a properly formatted input for GetKeyNameText. For more information about the function and the format of the first parameter to GetKeyNameText see the documentation at MSDN

Note: I used the W variant on the API calls, so you'd actually need to use a std::wstring to pass the key name, but you can change it easily to use the A version. Also, if you need to pass a keyboard layout to get the proper scan code, you can use MapVirtualKeyEx.

like image 145
theB Avatar answered Oct 28 '22 10:10

theB