How to convert UCHAR Virtual-Key Codes into std::string [duplicate]

Three problems in getKeyPressedString:
1) You´re not deleting lpszName again.
Either make a delete lpszName; before returning,
or use a static buffer in the first place.

2) keyString = *lpszName; only assigns the first character, not the whole string.
Remove *.

3) GetKeyNameText can fail. Check the return value, and GetLastError too.
(side note: ERROR_INSUFFICIENT_BUFFER won´t happen with key names and 256).


std::string Input::getKeyPressedString(UCHAR vkey)
    TCHAR lpszName[256];
    if(!GetKeyNameText(vkey, lpszName, sizeof(lpszName)))
        //maybe? Or throw std::systemerror(GetLastError(), std::system_category())
        return std::string("");
    return std::string(lpszName);

Leave a Comment