Using a string with the SendInput Function on Windows

大城市里の小女人 提交于 2021-01-29 10:11:29

问题


I want to use a std::string for the SendInput() function.

After doing some research, I found that the VkKeyScanEx might help but the code needs additional logic for uppercase or special characters. In the latter case I realized that I can simulate a SHIFT key press, send the lowercase key input and then it would come out as uppercase. However, there are also the "special" characters like !"§$%&/()=? which need a held down SHIFT key to come out correctly. Furthermore, there are also the umlauts like äüö. My code below works but the umlauts are also capitalized which is wrong for example (because isalnum() returns true for those as well). Isn't there a reasonable way of handling any string input and simulating it via the user's keyboard regardless of region, language and so on without causing such a logical mess? Isn't there a simpler and foolproof way to do this?

const auto key_board_layout = GetKeyboardLayout(0);

void configure_input(INPUT& input)
{
    input.type = INPUT_KEYBOARD;
    input.ki.wScan = 0;
    input.ki.time = 0;
    input.ki.dwExtraInfo = 0;
    input.ki.dwFlags = 0;
}

void send_input(const HWND window_handle, const std::string& message)
{
    SetForegroundWindow(window_handle);
    std::locale::global(std::locale("")); // Needed to not crash on certain special characters      

    for (auto character : message)
    {
        INPUT key_input;
        configure_input(key_input);

        INPUT shift_input;
        configure_input(shift_input);
        shift_input.ki.wVk = VK_SHIFT;

        // Type the key
        const auto virtual_key = VkKeyScanEx(character, key_board_layout);
        key_input.ki.wVk = virtual_key;
        const auto is_shift_key_required = isupper(character) || !isalnum(character);
        if(is_shift_key_required)
        {
            // Hold down the shift key
            SendInput(1, &shift_input, sizeof(INPUT));
        }
        SendInput(1, &key_input, sizeof(INPUT));

        // Release the key
        key_input.ki.dwFlags = KEYEVENTF_KEYUP;
        SendInput(1, &key_input, sizeof(INPUT));

        if(is_shift_key_required)
        {
            // Release the shift key
            shift_input.ki.dwFlags = KEYEVENTF_KEYUP;
            SendInput(1, &shift_input, sizeof(INPUT));
        }
    }
}

来源:https://stackoverflow.com/questions/59864053/using-a-string-with-the-sendinput-function-on-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!