简体   繁体   English

C++ 按下键

[英]C++ getting the key pressed

I am making a program and I want it to be able to read key presses.我正在制作一个程序,我希望它能够读取按键。 It does that just fine but I am running into some trouble when I am trying to get the name of the key that was pressed.它做得很好,但是当我尝试获取按下的键的名称时遇到了一些麻烦。 The code just stops in the middle of the program and for what part is ran it does not give the expected output.代码只是在程序中间停止,对于运行的部分,它没有给出预期的输出。 Here is my code.这是我的代码。

#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;
}

The output this gives me is这给我的输出是

Running....
Key:

and the output I am expecting is我期待的输出是

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

or at least something very close to that.或者至少是非常接近的东西。 It should display that those three hexadecimal numbers represent D, E, and F.它应该显示这三个十六进制数代表 D、E 和 F。

The test function is one I made to test turning the virtual key codes into the keys they represent but have so far been unsuccessful.测试功能是我用来测试将虚拟键代码转换为它们所代表的键但迄今为止未成功的功能。 Any help is appreciated!任何帮助表示赞赏!

Read the documentation.阅读文档。 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() expects a hardware scan code instead (amongst other flags), such as from the LPARAM of a WM_KEY(DOWN|UP) message. MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR)不是有效输入GetKeyNameTextW()作为要映射的虚拟键码为一个字符,但GetKeyNameTextW()需要一个硬件扫描代码,而不是(在其他标志),诸如从LPARAM一个的WM_KEY(DOWN|UP)消息。

You are also not ensuring that your key[] buffer is null-terminated if GetKeyNameTextW() fails, so you risk passing garbage to std::wcout .如果GetKeyNameTextW()失败,您也不能确保您的key[]缓冲区以空值终止,因此您可能会冒险将垃圾传递给std::wcout

In this case, virtual key codes 0x44 .. 0x46 can be output as-is once converted by MapVirtualKeyW() , there is no need to use GetKeyNameTextW() for them, eg:在这种情况下,虚拟键码0x44 .. 0x46可以按MapVirtualKeyW()输出,一旦被MapVirtualKeyW()转换,就不需要对它们使用GetKeyNameTextW() ,例如:

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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