简体   繁体   English

C++ 读取键盘事件

[英]C++ read keyboard events

I am new to C++ and I am trying to make a program that reads keystrokes.我是 C++ 的新手,我正在尝试制作一个读取按键的程序。 This is a function I made that looks for a certain key.这是我制作的一个寻找某个键的函数。

void printKey(short vk)
{
    if ((GetAsyncKeyState(vk) >> 15) & 1)
    {
        LPWSTR key;
        GetKeyNameTextW(MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR) << 16, key, sizeof(key));
        wcout << key;
    }
}

I know that the key detection works as I have put code that just prints true or false inside of the if statement so I know that that part is working.我知道关键检测有效,因为我在 if 语句中放置了仅打印 true 或 false 的代码,因此我知道该部分正在工作。 For example when I type "s" it prints true if I pass in the virtual key code 0x53 (virtual key code for s).例如,当我输入“s”时,如果我传入虚拟键代码 0x53(s 的虚拟键代码),它会打印 true。 Once I knew that part worked I tried to use the MapVirtualKeyW and GeyKeyNameTextW functions to get the name of the key so I wouldn't have to hard code all of them in. The code compiles but stops immediately after printing Running....一旦我知道那部分工作,我就尝试使用 MapVirtualKeyW 和 GeyKeyNameTextW 函数来获取密钥的名称,这样我就不必硬编码所有这些。代码编译但在打印后立即停止Running....

Here is the whole code这是整个代码

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

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

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

void printKey(short vk)
{
    if ((GetAsyncKeyState(vk) >> 15) & 1)
    {
        LPWSTR key;
        GetKeyNameTextW(MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR) << 16, key, sizeof(key));
        wcout << key;
    }
}

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

    while (true)
    {
        for (int i = 48; i <= 90; i++)
        {
            printKey(i);
        }
    }

    return 0;
}

the range 48-90 is for all the letter and number keys.范围 48-90 用于所有字母和数字键。 The idea is that whenever I press a key it should print to the console.这个想法是,每当我按下一个键时,它应该打印到控制台。

I am fairly confident the issue is in this block of code我相当有信心问题出在这段代码中

LPWSTR key;
GetKeyNameTextW(MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR) << 16, key, sizeof(key));
wcout << key;

Any help is appreciated!任何帮助表示赞赏!

In addition to the comments above, GetKeynameText needs a buffer for the key name, so instead of:除了上面的注释之外, GetKeynameText需要一个用于键名的缓冲区,而不是:

LPWSTR key;
GetKeyNameTextW(MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR) << 16, key, sizeof(key));

you want something like:你想要这样的东西:

WCHAR key [128];
GetKeyNameTextW(MapVirtualKeyW(vk, MAPVK_VK_TO_CHAR) << 16, key, sizeof(key) / sizeof (WCHAR));

You might also flush wcout after writing to it.您也可以在写入后刷新wcout

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

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