0

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);
            }
        }
    }
}

ItsDave
  • 1
  • 1
  • 1
    *however I'm uncertain if it is very efficient.* -- If the code works, questions like this should go to [Code Review](https://codereview.stackexchange.com/questions/tagged/c%2B%2B). Having said this, this looks like a whole lot of code to simply toggle a boolean flag, for example: `bool isOn = true;... IsOn = !IsOn;...}` whenever the key is hit. Then simply: `std::cout << (isOn?"On":"Off");` – PaulMcKenzie Aug 02 '21 at 05:15
  • I apologize if I posted this in the incorrect place! I'm brand new to SO and C++ (This is a personal project I'm working on while taking a course). I used the while loops so that I could constantly check the keyState. Are you saying they're completely redundant? – ItsDave Aug 02 '21 at 05:29
  • Get the initial key state before the loop, set the boolean to either on or off depending on that value. Then all of that duplicate code within the loop is whittled down to maybe 3 lines by simply toggling that single boolean value when the key is hit. No need to check for key being off or on, just toggle the boolean. – PaulMcKenzie Aug 02 '21 at 05:31
  • Much appreciated, I'll try to keep dumb questions out of here, so sorry. – ItsDave Aug 02 '21 at 05:37
  • This isn't just inefficient, it also doesn't work. Put your system under load and you'll start seeing the code missing key presses. Polling is always wrong. Polling is literally **always** wrong on Windows. What you want is an event-driven program. Register a hotkey, install a Raw Input hook, or install a low-level keyboard hook and respond to keyboard input events. No needless system load anymore, and no opportunity to miss keyboard input. – IInspectable Aug 02 '21 at 07:51

0 Answers0