GetAsyncKeyState Toggling

421 Views Asked by At

I'm trying to make a very basic 'switch' that will toggle by pressing the HOME key. I've come up with a solution that will display "Off." or "On." in console depending on whether "bool homeKeyWasDown" is true or false. So, I have technically achieved my goal, however I'm uncertain if it is very efficient. Is there some other means that I'm missing here?

#include <iostream>
#include <windows.h>
#pragma comment(lib, "user32.lib")
#include <stdlib.h>
using namespace std;

int main()
{
    SHORT homeKey;
    bool homeKeyWasDown = false;

    homeKey = GetAsyncKeyState(VK_HOME);
    while (homeKeyWasDown == false) {
        homeKey = GetAsyncKeyState(VK_HOME);
        cout << "Off.";
        Sleep(100);
        system("CLS");

        while (homeKey != 0) {
            homeKey = GetAsyncKeyState(VK_HOME);
            homeKeyWasDown = true;
            Sleep(100);
        }
        
        while (homeKeyWasDown == true) {
            homeKey = GetAsyncKeyState(VK_HOME);
            cout << "On.";
            Sleep(100);
            system("CLS");
            
            while (homeKey != 0) {
                homeKey = GetAsyncKeyState(VK_HOME);
                homeKeyWasDown = false;
                Sleep(100);
            }
        }
    }
}

0

There are 0 best solutions below