c++ - 虚拟键码到 unicode 的映射受写入 std::cout 的影响?

标签 c++ winapi keypress

我遇到了一个奇怪的问题,我真的不知道如何解决。我正在用 C++ 编写代码,它应该在按下键时触发事件。我可以使用 GetAsyncKeystate 检测按键并正常释放,但我无法可靠地将检测到的按键状态转换为 unicode。 (请注意,我使用的是 Qt,但这并不重要)

我的按下/释放检测:

// This function is called in a loop
void KeyboardApi::Check()
{
    bool stat = false;
    for (int i = 7; i < 255; i++) { // 0 undefined, 3 VK_CANCEL can be ignored, 1 2 4 5 6 mouse keys, these are ignored
        stat = ((GetAsyncKeyState(i) & 0x8000) != 0);

        if (this->first_time) { // To prevent reporting keypresses upon initialization
            this->first_time = false;
            this->keystate[i] = stat;
            continue;
        }

        if (stat != this->keystate[i]) {
            this->keystate[i] = stat;

            if (i == VK_SHIFT)
                this->shift = stat;
            else if (i == VK_CONTROL)
                this->ctrl = stat;
            else if (i == VK_MENU)
                this->alt = stat;

            HKL locale = GetKeyboardLayout(GetCurrentThreadId());

            // ---!! If this portion is commented, the code does not work correctly.
            //       if this portion is *not* commented, the code works fine...
            /*
            std::wcout << "args for keycode_to_unicode:" << std::endl
                       << "  keycode: " << i << std::endl
                       << "  locale: " << locale << std::endl
                       << "  shift: " << this->shift << std::endl;
            */
            // ---!!

            QString key_string = keycode_to_unicode(i, locale, this->shift);

            if (stat)
                std::wcout << "Key pressed:  " << i <<  " unicode: " << key_string.toStdWString() << std::endl;
        }
    }
}

以及 keycode_to_unicode 函数:

QString keycode_to_unicode(unsigned int key, HKL keyboardLayoutHandle, bool shiftPressed)
{
    int scanCodeEx = MapVirtualKeyExW(key, MAPVK_VK_TO_VSC_EX, keyboardLayoutHandle);

    if (scanCodeEx > 0) {
        unsigned char lpKeyState[256];

        if (shiftPressed) {
            lpKeyState[VK_SHIFT] = 0x80;
            lpKeyState[VK_LSHIFT] = 0x80;
        }

        wchar_t buffer[5];

        int rc = ToUnicodeEx(key, scanCodeEx, lpKeyState, buffer, 5, 0, keyboardLayoutHandle);

        if (rc > 0) {
            return QString::fromWCharArray(buffer);
        } else {
            // It's a dead key; let's flush out whats stored in the keyboard state.
            rc = ToUnicodeEx(key, scanCodeEx, lpKeyState, buffer, 5, 0, keyboardLayoutHandle);
            return QString();
        }
    }

    return QString();
}

所以奇怪的是,当我在那里有调试输出时,KeyboardApi::Check() 工作正常,但是当我没有它时,到 unicode 的转换就会出错。例如,当我第一次按'A'键时,输出'a'。第二次,'β','β'等。

编辑: 你可能会问自己为什么我不使用 Qt 的内置 onKeyPress...这是因为我的代码被注入(inject)到其他进程中,因此我不能使用这种方法。

最佳答案

原来是keycode_to_unicode的问题!

在我的代码中,我有:

unsigned char lpKeyState[256];

表示数组没有初始化;它的内容可以是任何东西。将其替换为:

unsigned char lpKeyState[256] = {0};

修复了奇数输入的问题。事实证明我还有一些其他问题(特别是死键)。我稍微修改了我的代码,现在可以在按下死键时正确检测到它们,尽管我还没有成功地将死键与后续字符结合起来以检测带有重音的字符。为了完整起见,修改后的代码如下:

注意:它考虑大写锁定。

QString KeyboardApi::keycode_to_unicode(unsigned int key, HKL keyboardLayoutHandle, bool shiftPressed, bool ctrlPressed, bool altPressed, bool capslock)
{
    int scanCodeEx = MapVirtualKeyExW(key, MAPVK_VK_TO_VSC_EX, keyboardLayoutHandle);

    if (scanCodeEx <= 0)
        return QString();

    unsigned char lpKeyState[256] = {0};

    if (shiftPressed) {
        lpKeyState[VK_SHIFT] = 0x80;
        lpKeyState[VK_LSHIFT] = 0x80;
    }

    if (ctrlPressed)
        lpKeyState[VK_CONTROL] = 0x80;

    if (altPressed)
        lpKeyState[VK_MENU] = 0x80;

    if (capslock)
        lpKeyState[VK_CAPITAL] = 0x01;

    wchar_t buffer[5];

    ToUnicodeEx(key, scanCodeEx, lpKeyState, buffer, 5, 0, keyboardLayoutHandle);

    QString ret = QString::fromWCharArray(buffer);
    ret.truncate(1);

    return ret;
}

Qt::Key KeyboardApi::unicode_to_qtkey(QString key)
{
    unsigned int code = key[0].unicode();
    if (key[0].unicode() >= 'a' && key[0].unicode() <= 'z') {
        code = key[0].unicode() - 'a' + Qt::Key_A;
    }

    return (Qt::Key)code;
}

void KeyboardApi::Check()
{
    bool init = this->first_time;

    if (this->first_time)
        this->first_time = false;

    bool stat = false;
    for (int i = 7; i < 255; i++) { // yes, 255 is NOT valid! // 0 undefined, 3 VK_CANCEL can be ignored, 1 2 4 5 6 mouse keys
        stat = ((GetAsyncKeyState(i) & 0x8000) != 0);

        if (stat == this->keystate[i])
            continue;

        this->keystate[i] = stat;

        if (i == VK_SHIFT)
            this->shift = stat;
        else if (i == VK_CONTROL)
            this->ctrl = stat;
        else if (i == VK_MENU)
            this->alt = stat;
        else if (i == VK_CAPITAL)
            this->capslock = stat;

        HKL locale = GetKeyboardLayout(GetCurrentThreadId());

        QString key_string = keycode_to_unicode(i, locale, this->shift, this->ctrl, this->alt, false);

        // See qkeymapper_win.cpp for the table used to convert windows virtual key codes to Qt::Key
        Qt::Key key = key_string.isEmpty() ? (Qt::Key)win_vk_to_qt_key[i] : unicode_to_qtkey(key_string);

        if (init || i == VK_SHIFT || i == VK_CONTROL || i == VK_MENU)
            continue;

        if (stat) {
            emit this->OnKeyDown(this, QKeyEvent(QEvent::KeyPress, key, mods, key_string));
        } else
            emit this->OnKeyUp(this, QKeyEvent(QEvent::KeyPress, key, mods, key_string));
    }
}

关于c++ - 虚拟键码到 unicode 的映射受写入 std::cout 的影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24955875/

相关文章:

Javascript - 检查用户是否正在编辑文本输入

c++ - 构图模式

c++ - OpenCL 中主机和设备的 64 位数据类型

c++ - 为什么我不能用 "\x"初始化字符串

c++ - glBufferData 带有一个顶点数组,每个顶点有 3 个 float (x、y 和 z)

c++ - 将 GetLastError() 转换为带有错误字符串的异常

c++ - 进程 ID 函数出现错误 "ERROR_NO_MORE_FILES"

javascript - 跟踪第一个按键事件

C++ directx 9 网格纹理

.net - Control + Enter/Return 键发送什么字符值?