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")
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.)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With