C++ (Windows): Convert a virtual key code string representation ("VK_F6") to hexadecimal (0x75)

  c++, scancodes, virtual-keyboard, windows

Is there an elegant way in C++ (Windows) to take string representation of a virtual key code (e.g. VK_NUMPAD0, VK_F6, VK_INSERT, VK_RSHIFT, etc.) and convert it to its corresponding hexadecimal value (e.g. 0x60, 0x75, 0x2D, 0xA1, etc.)? Currently, I know using a switch statement, if statement, map, etc. will work (and I am using this technique) but these all seem clunky and inelegant (they are "hard coded" and may not be the most universal) solutions. I would imagine there must be some API designed specifically for this kind of task.

I checked the MSDN documentation for any API’s that may help but the closest ones I found were VkKeyScan, MapVirtualKey, and maybe ToAscii but none of these seemed to be what I am looking for (or at least I do not know the combination to use them). I know I am missing something and probably just not knowing the right think to look for.

Expectation (pseudo code):

auto key_pressed = GetVkFromString("VK_F6"); // gets 0x75

In the same vein, is there a cross-platform solution? I know the VK_ constants are Windows specific but I am curious to know if there are alternative solutions that work on multiple platforms (incl. Windows). I don’t need to support them at the moment but it is always something I like to keep in mind.

Just in case someone asks if this is an X vs Y problem or thereabouts, the reason for this is that we are using a semi-user friendly config file (JSON) that allows for various commands in our app to be bound to keys (and changed if the user so chooses). We want to have this file be a relatively easy file to edit without needing to put awkward data types in it like hexadecimals.

Source: Windows Questions

LEAVE A COMMENT