Search code examples
c++winapiunicodesendinputdirectinput

Can't convert from virtual key code to unicode


I need to inject text into directinput applications. I'm using SendInput, but using virtual key codes doesn't work with directinput, so I need to use Unicode. Now, the keys I wan't to inject are registered on a file as virtual key codes, and i need to convert them to Unicode in real time.

return1 = ToUnicode(vk, MapVirtualKey(vk, MAPVK_VK_TO_VSC), NULL, buffer, 1, 0);

This is my code string. vk is the virtual key in a int, and buffer is a wchar_t array large 1 unit. I couldn't use just a simple wchar_t because it didn't work with ToUnicode. However, this function just returns 0 everytime, thus meaning the function couldn't translate the key. For the record, i'm using standard keys, such as "wasd", no special characters. If anyone can make out why this happens, I would really like some help.

Thanks for the consideration!

EDIT: also, would it be convenient to just fight my laziness and write some old switch and break to convert the values? eg.

wchar_t unicode;
switch (vk)
case '0x30':
    unicode = '48';
    //ecc...

Solution

  • It says that the "keys" array is optional, but unless I pass in a keys I get a zero result too. Maybe they just mean you have the option of having it work or not?

    std::vector<BYTE> keys(256, 0);
    int sc = MapVirtualKey(vk, MAPVK_VK_TO_VSC);
    return1 = ToUnicode(vk, sc, keys.data(), buffer, 1, 0);
    

    So try that (or &keys[0] instead of keys.data() if you're not using C++11).