C ++获取按键

C++ getting the key pressed

我正在制作一个程序,我希望它能够读取按键。它做得很好,但是当我试图获取按下的键的名称时,我 运行 遇到了一些麻烦。代码只是停在程序的中间,对于 运行 的部分,它没有给出预期的输出。这是我的代码。

#include <iostream>
#include <Windows.h>

#pragma comment(lib, "User32.lib")

using std::cout;
using std::endl;
using std::wcout;

void test(short vk)
{
    WCHAR key[16];
    GetKeyNameTextW(MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR), key, _countof(key));
    wcout << "Key: " << key << endl;
}

int main()
{
    cout << "Running...." << endl;

    test(0x44); // Key: D
    test(0x45); // Key: E
    test(0x46); // Key: F

    return 0;
}

这给我的输出是

Running....
Key:

我期望的输出是

Running....
Key: D
Key: E
Key: F

或者至少是非常接近的东西。它应该显示这三个十六进制数分别代表 D、E 和 F。

测试功能是我用来测试将虚拟键码转换为它们所代表的键的功能,但到目前为止没有成功。感谢您的帮助!

阅读文档。 MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR) is not valid input for GetKeyNameTextW(), as you are mapping a virtual key code to a character, but GetKeyNameTextW() 需要硬件扫描码(以及其他标志),例如来自 WM_KEY(DOWN|UP) 消息的 LPARAM

如果 GetKeyNameTextW() 失败,您也不能确保 key[] 缓冲区是 null-terminated,因此您冒着将垃圾传递给 std::wcout 的风险。

这种情况下,虚拟键码0x44..0x46可以输出as-is,经过MapVirtualKeyW()转换后,就不用[=12了] =] 给他们,例如:

void test(short vk)
{
    UINT ch = MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR);
    if (ch != 0) {
        wcout << L"Key: " << (wchar_t)ch << endl;
    }
    else {
        wcout << L"No Key translated" << endl;
    }
}