简体   繁体   中英

How can I easily convert a string to a keyboard character

Yeah, i'm doing hotkey parsing and I could do with an easy way to convert from string to keyboard character rather than writing a whole parser
For example: "F6" -> VK_F6

Such types of conversion can easily be done with lookup tables. In C++ you could use std::map for this purpose. There are many other possibilities.

Please see example below:

#include <iostream>
#include <map>
#include <string>

constexpr unsigned int VK_F1 = 0x70;
constexpr unsigned int VK_F2 = 0x71;
constexpr unsigned int VK_F3 = 0x72;
constexpr unsigned int VK_F4 = 0x73;
constexpr unsigned int VK_F5 = 0x74;
constexpr unsigned int VK_F6 = 0x75;

std::map<std::string, unsigned int> lookup{
    {"F1", VK_F1},
    {"F2", VK_F2},
    {"F3", VK_F3},
    {"F4", VK_F4},
    {"F5", VK_F5},
    {"F6", VK_F6},
};

int main() {

    unsigned int virtualKeyCode{ 0 };
    std::string keyString{};

    keyString = "F6";
    virtualKeyCode = lookup[keyString];

    std::cout << std::hex << virtualKeyCode << "\n";

    return 0;
}

Of course you need to extend for further keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM