How can I implement a function like std::string VirtualKeyCodeToStdString(UCHAR key) which returns virtual keys descriptions?
Example: input is VK
A simple way to convert the VK code to a text representation of the key is to:
MapVirtualKey to convert the VK code to a scan code.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.