按下shift键时没有控制台按键事件

时间:2017-01-14 03:28:27

标签: c windows winapi console

我有一段代码,它将使用ReadConsoleInput函数从控制台读取一个键事件。它主要起作用,除了在按下shift键时释放按钮时无法读取。

我写了最简单的示例代码。它现在做的是读取是否按下'a'键并将其显示在屏幕上。如果你运行它并按'a'即可获得

41[down]
41[up]

如果你按下'a'之前按住Shift键,你得到的只是

41[down]

并且在释放shift键并再次按“a”之前,您将无法获得按键事件。

这是我的代码:

#include <stdlib.h>
#include <stdio.h>
#include <Windows.h>
#include <Tchar.h>

int main()
{
    HANDLE rhnd = GetStdHandle(STD_INPUT_HANDLE);

    while(1)
    {

        INPUT_RECORD buf[128];
        DWORD Events = 0;
        DWORD EventsRead = 0;

        GetNumberOfConsoleInputEvents(rhnd, &Events);
        if(Events == 0)continue;
        int i;
        for(i=0;i<sizeof(buf);++i)//clear buf in case ReadConsoleInput doesn't do it for me, probably unnecessary
            ((char *)buf)[i]=0;
        ReadConsoleInput(rhnd, buf, 128, &(EventsRead));
        for(i=0;i<128;++i)//I would just loop while i<EventsRead but this ensures there are not extra elements (a little paranoid, I know)
        {
            if(buf[i].EventType == KEY_EVENT && (buf[i].Event.KeyEvent.wVirtualKeyCode & 0xff) == 0x41 /*keycode for 'a' button -- you can remove this condition to see the results for all key presses*/)
            {
                printf("%x",buf[i].Event.KeyEvent.wVirtualKeyCode);
                if(buf[i].Event.KeyEvent.bKeyDown)
                {
                    printf("[down]\n");
                }
                else //if this else gets executed it's what I'm calling a key up event
                    //this conditional should only be reached if either 'a' is pressed or 'a' was just released
                   //and the else should only be executed if it was just released
                {
                    printf("[up]\n");
                }
            }
        }
    }
}

关于为什么会发生这种情况以及如何解决问题的任何想法

使用gcc(MinGW-64)和使用Visual Studio 15

在Windows 10上编译

0 个答案:

没有答案