如何检测C ++中是否按下了特定键盘键以外的任何键盘键?

时间:2018-03-31 07:34:10

标签: c++ keyboard-input

我有以下代码可以正常工作。

int x = 0;
int main()
{    
    while(true) {   
        if (GetKeyState('A') & 0x8000 && x == 0) {
            Sleep(500);
            x = 1;
        }
        else if (GetKeyState('B') & 0x8000 && x == 1) {
            Sleep(500);
            x = 2;
        }
        else if (GetKeyState('C') & 0x8000 && x == 2) {
            Sleep(500);
            x = 0;
            //Do Something
        }
    }
}

为了执行代码的//Do Something部分,用户必须首先按A,然后按B然后按C按此顺序。但是,用户可以按任意键,它仍然可以工作。除了" A + B + C"以下内容也适用。

  1. A + C + B + C
  2. A + Q + B + C
  3. A + F11 + B + 8 + LSHIFT + Spacebar + Tab + C
  4. 我只希望A + B + C组合起作用。不是以上任何一种。

    我试图实现的代码有点像这样

    int x = 0;
    int main()
    {
        while(true) {
    
            if (GetKeyState('A') & 0x8000 && x == 0) {
                Sleep(500);
                x = 1;
            }
            else if (GetKeyState('B') & 0x8000 && x == 1) {
                Sleep(500);
                x = 2;
            }
            else if (GetKeyState(/*Any keyboard input other than 'B' or 'A'*/) & 0x8000 && x == 1) {
                Sleep(500);
                x = 0;
            }
            else if (GetKeyState('C') & 0x8000 && x == 2) {
                Sleep(500);
                x = 0;
                //Do Something
            }
            else if (GetKeyState(/*Any keyboard input other than 'C' or 'B'*/) & 0x8000 && x == 2) {
                Sleep(500);
                x = 0;
            }
        }
    }
    

    所以你看我理解了所需的逻辑。我只是不知道更换代码注释部分所需的正确代码。请注意,我在评论中输入两个键的原因是因为用户可能会意外按键两次或三次,因为他/她需要原谅,而且代码仍需要工作。

    我想我已经尽力让这个问题尽可能理解。如果没有建议编辑的话。

1 个答案:

答案 0 :(得分:1)

在Windows上,为简单起见,您可以使用_kbhit(),除非您有特殊原因要使用GetKeyState

#include <iostream>
#include <conio.h>  

int main()
{
    int x = 0;
    while (true)
    {
        if (!_kbhit())
            continue;

        switch (_getch())
        {
        case 'A':
            x == 0 ? ++x : x = 0;
            break;
        case 'B':
            x == 1 ? ++x : x = 0;
            break;
        case 'C':
            x == 2 ? ++x : x = 0;
            break;
        default:
            x = 0;
        }

        if (x == 0)
            std::cout << "Oops!" << std::endl;
        else if (x == 3)
        {
            std::cout << "Bingo!" << std::endl;
            break;
        }
    }
}
相关问题