我按下键时无法检测到GetKeyboardState

时间:2016-05-10 15:23:34

标签: c++ winapi keyboard

我想了解GetKeyboardState()的工作原理。我已经阅读了Keyboard Input Model中虚拟键的介绍 和GetKeyboardState() documentation

根据我的理解,GetKeyboardState()应该声明它返回的数组中的所有键状态。因此,当我打开和关闭 Caps Lock 键时,我试图查看以下代码是否有任何差异:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <string.h>
#include <windows.h>
#include <iostream>
int main(int argc, char *argv[])
{
    INPUT buffer[1];
    bool stop = false;
    unsigned char kbstate[256];
    int timer = 0;
    MouseSetup(buffer);
    char result = 0;
    //doesn't work right now
    do{

        timer++;
        Sleep(3000);
        std::cout << "function output: " << GetKeyboardState(kbstate) << std::endl;
        for (int i = 0; i < 256; i++) {
            std::cout << (int)kbstate[i];
            if (i % 16 == 0){
                std::cout << std::endl;
            }
        }
        std::cout << std::endl;
    } while (!result);
    return 0;
}

我的cap和uncap的输出都是一样的。

我想我理解GetKeyboardState()的方式是错误的。有人能告诉我哪里出错了吗?

没关系,我明白了。这是我真正想做的事情。非常感谢所有帮助人员。

int main(int argc, char *argv[])
{
    INPUT buffer[1];
    bool stop = false;
    unsigned char ifPress[256];
    int timer = 0;
    char result = 0;
    std::cout << "press any key to quite" << std::endl;
    do{
        timer++;
        Sleep(100);
        //check all the status if any key is pressed
        for(int i = 0; i < 256; i++) {
            ifPress[i] = GetAsyncKeyState(i);
        }
        //if any key is pressed, change the status to the result
        //and the loop will be quit
        for (int j = 1; j < 256; j++){
            result = result || ifPress[j];
        }
    } while (!result);
    return 0;
}

1 个答案:

答案 0 :(得分:-2)

尝试从此代码中学习

#include <iostream>
#include <string>
#include <Windows.h>
int main()
{
    int temp;
    BYTE arr[256];
    while(1)
    {
        memset(arr,0,sizeof(256));
        GetKeyState ( 0 ) ;
        if(GetKeyboardState(arr))
        {    
             for(int i=0;i<256;i++)
            {
                temp=(int)arr[i];
                temp>>=7;
                std::cout<<temp;
            }
            std::cout<<std::endl;
            Sleep(5000);
        }
    }
}