C++: GetKeyState() has to run once

16,291

Your functions are called multiple times because of the duration time the button stays pressed. The system is very sensitive. So this is a workaround.

You could do something like this (set a flag that will assign a value when the key is down, and then reasign it when the key is up).

int k=0;//Flag
while(1){
    //check if the key was pressed (key_down)
    if((GetAsyncKeyState('0') & 0x8000) && (k == 0)){k=1; cout<<"'0' PRESSED."<<k<<endl;}//do your stuff here
    //check if the key was released (key up)
    else if(GetAsyncKeyState('0') == 0) k = 0;//reset the flag
}
Share:
16,291
Aristona
Author by

Aristona

Hi there! I'm Anıl and I live in Kastamonu, Turkey. Although my main expertise is on the backend, I usually do frontend, mobile development and game development too.

Updated on June 04, 2022

Comments

  • Aristona
    Aristona almost 2 years

    I need to listen keyboard key states for my tiny application.

    #include <windows.h>
    #include <fstream>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        while(1)
        {
            if(GetKeyState(VK_SPACE) & 0x80)
            {
                cout << "Space pressed.\r\n";
                DoSpaceKeyTask();
            }
    
            if(GetKeyState(OTHER_KEY) & 0x80)
            {
                cout << "Other key pressed.\r\n";
                DoOtherKeyTask();
            }
        }
        return 0;
    }
    

    Once I click some keys from my keyboard, these functions has to run once. They're just some tiny tasks for my applications, which is not related in this topic.

    My problem is, when I press a key, it executes the functions few times, due to while(1) looping few times during key press. I cannot use Sleep() in this case, because it still won't be effective.

    I'm looking for a solution like this.

    1. I press SPACE key.
    2. DoSpaceKeyTask() executes "once."
    3. I press OTHER key.
    4. DoOtherKeyTask() executes "once."

    I have like 5 keys that I will be using. Could anyone help me on this case?

    Ps. If GetKeyState() function isn't useful on this task, feel free to suggest yours. My function knowledge is pretty limited on C++.