0

In my Windows command line program, I'm waiting for the user to press the left shift and left click keys simultaneously to continue the execution of the rest of the program. The command prompt will not be in focus when the key combo is pressed.

My current code is:

#include <iostream>
#include <windows.h>

int main()
{

  std::cout << "Press left shift and left click to start\n";

  // GetKeyState() returns 0 or 1 when key is not pressed, and -127 or -128 when key is pressed
  while (GetKeyState(VK_LSHIFT) >= 0 || GetKeyState(VK_LBUTTON) >= 0) {
    ;
  }

  std::cout << "Starting\n";

}

The current code works. However, when waiting for the user to enter the key combo, CPU utilisation of a single core is at 100%.

Is there a non-CPU intensive way of waiting for the user to enter a key combo?

George Tian
  • 401
  • 7
  • 16
  • 1
    why not to sleep a bit (like 20 milliseconds)? – Maxim Sagaydachny Jul 09 '20 at 09:49
  • At least, you could add a [Sleep()](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep) to the `while()` body. I would use not less than 50 ms but 100 ms would probably do as well. (100 ms is round about the perception threshold of humans.) 50 or 100 ms sleeping is short for a user but looong for the CPU. This should lower the noise of the cooler. That said, the sophisticated way would be to use blocking input (maybe, in a separate thread) or to add event processing. – Scheff's Cat Jul 09 '20 at 09:50
  • @MaximSagaydachny Thank you for the suggestion to sleep, it definitely solved the high CPU usage issue. – George Tian Jul 09 '20 at 10:03
  • @Scheff Thank you, sleeping solves the problem. However, could you guide me towards resources explaining the sophisticated ways you've mentioned? – George Tian Jul 09 '20 at 10:04
  • _However, could you guide me towards resources explaining the sophisticated ways you've mentioned?_ Actually, I cannot. ;-) (It actually was meant as some kind of disclaimer against future re-comments.) Concerning event processing, this would be Windows specific code I'm not experienced in. (I always try to write portable code.) Concerning blocking input in a separate thread, I once wrote an answer to [SO: I/O in concurrent program](https://stackoverflow.com/a/48097134/7478597) but I'm afraid that it won't cover the specific key combination you intend. Tl;dr: IMHO, `Sleep()` is fine for you. – Scheff's Cat Jul 09 '20 at 10:09

0 Answers0