简体   繁体   English

SetKeyboardState无法正常工作

[英]SetKeyboardState doesnt work properly

I have program, then it's running it asks stuffs and then user has to press 1 to proceed I use GetKeyState() function to decide if number was pressed and SetKeyboardState() to set keys states back to original, but it doesn't work after second attempt. 我有程序,然后它运行它询问东西,然后用户必须按1继续我使用GetKeyState()函数来决定是否按下了数字和SetKeyboardState()将键状态设置回原始状态,但它不起作用第二次尝试。 Whats wrong? 怎么了?

Code: 码:

BYTE States[256];
GetKeyboardState(States); 

cout << press 1 << endl;

while(!Started)
{
    if(GetKeyState(VK_NUMPAD1))
    {
        Started = true;
    }
}

SetKeyboardState(States);

cout << "press 1" << endl;

while(!Name)
{
    if(GetKeyState(VK_NUMPAD1))
    {
        Name = true;
    }
}

SetKeyboardState(States);

cout << "press 1" << endl;

while(!Located)
{
    if(GetKeyState(VK_NUMPAD1))
    {
        Located = true;
    }
}

I am no expert, but as far as I can see, Your while(!Name) checks if variables are false. 我不是专家,但据我所知,你的while(!Name)检查变量是否为假。 Inside the loop you set them to true and loop ends which leaves you unable to check key more then once. 在循环内部,您将它们设置为true,循环结束,这使您无法再检查一次键。

The code looks a bit odd to me. 代码对我来说有点奇怪。 I have a feeling that you've not got the optimal solution to your problem. 我觉得你没有找到解决问题的最佳方案。 But I don't know enough of your problem to say so for sure. 但我肯定不清楚你的问题。

One thing sticks out though. 但有一件事情很突出。 Your test of the return value of GetKeyState() is wrong you should test it like this: 您对GetKeyState()的返回值的测试是错误的,您应该像这样测试它:

if(GetKeyState(VK_NUMPAD1)<0)

From the documentation: 从文档:

If the high-order bit is 1, the key is down; 如果高位为1,则键为关闭; otherwise, it is up. 否则,它就结束了。

The simple way to test for high-order bit being 1 is that the value is negative. 测试高阶位为1的简单方法是该值为负。 Your code tests for any bit being set which will evaluate true for states other than the key being down. 您的代码将测试所设置的任何位,该值将针对除关键之外的状态评估为true。

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

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