Key listener to exit the loop only when the program is in focus (C ++)

I wrote a C ++ console program that displays a menu with several parameters for the user, one of which goes into a continuous loop, and the condition for exiting the loop is GetAsyncKeyState (VK_ESCAPE). Therefore, if the user presses ESC, the next time this cycle is started, he will exit and the main menu will be displayed again.

The problem occurs when the user does not have my program in focus and press the ESC key, GetAsyncKeyState will still return that the ESC key is pressed and the loop will exit.

How can I implement a solution that will listen to the ESC key only when my program is in focus?

  • I cannot use getline, getch or any string input methods because I will have a loop and I cannot request user input at each iteration.
  • The solution may be platform dependent, as it will only work on Windows.
  • I need to stick with C ++ because I use a library, the only "used" version is the C ++ version.

This can be useful for anyone writing a C ++ console program that has a loop that exits when a key is pressed and the program is in focus.

Thanks in advance!

+4
source share
1 answer

GetForegroundWindow . .

@NathanOliver, IsWindowEnabled, , true, , . IsWindowVisible, , , ESC, . , , GetForegroundWindow(), , , , GetConsoleWIndow (), , , , GetKeyState (VK_ESC), !

HWND hWnd = GetConsoleWIndow();
boolean leaveAuto = false;
while(!leaveAuto) {
  ...
  leaveAuto = (GetAsyncKeyState(VK_ESCAPE) && (GetForegroundWindow() == hWnd));
}

: , ESC, , GetAsyncKeyState true, , , -, ESC, , - , . , , ESC, .

ESC, .

+1

All Articles