GetAsyncKeyState() after system("PAUSE")

I am looking for a way to wait for either an Escape or Return keypress and ignore all others. Escape should break out of the loop, and return should print, take a user input, then continue the loop.

Escape breaks the loop as expected. The problem I am having is that any key that isn't Escape will take me into the else if clause, but it should only do that for Return. I am wondering if going into the `else if` block has something to do with System("PAUSE") or hitting enter after taking a user input.

Why am I going into the else if block unexpectedly, and what would be a better way of pausing until one of these keys is pressed?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
while (1) {

	// Wait until next keypress
	system("PAUSE");

	// Escape keypress ends the loop
	if (GetAsyncKeyState(VK_ESCAPE) != 0) {
		break;
			
	} else if (GetAsyncKeyState(VK_RETURN) != 0) {
		// Enter key does the action
		std::cout << "Enter Pressed. Taking user input." << endl;
		std::cin >> foo;
	}
}
Last edited on
You can use _getch() in the conio.h library. It'll wait for user input (without waiting for the enter key) and wont mess with it so your if statements will work fine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <Windows.h>
#include <conio.h>

int main()
{
	while (_getch())
	{
		// Escape keypress ends the loop
		if (GetAsyncKeyState(VK_ESCAPE))
		{
			std::cout << "FAIL";
			break;

		}
		else if (GetAsyncKeyState(VK_RETURN))
		{
			// Enter key does the action
			std::cout << "Enter Pressed. Taking user input." << std::endl;
			//std::cin >> foo;
		}
	}
}
Topic archived. No new replies allowed.