Detecting pressed keys

Jun 28, 2012 at 6:42pm
Hi, I'm working on a small labyrinth game (you got a hero, you move around and kill monsters) and I was wondering if there is a way besides Win API(the only thing I found on the internet) to detect the keys that are pressed.

I ask this because when I want to move my hero I have to tell it where to go (W,A,S,D) and then press enter. Is there something that will automatically do this? If not, do you happen to know the simplest way to do something similar or include the respective piece of code in my project?

I'm running windows in case you ask and didn't realize :D

Thanks in advance,
Chris
Jun 28, 2012 at 7:37pm
You could use the _getch() function in the conio.h header file. It works with MSVC++, but I'm not sure with other IDEs. If compatibility is very important to you, you may want to find another way.

Here's an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <conio.h>

int main()
{
	char ch; //or 'int ch;' (it doesn't really matter)

	//the program pauses here until a key is pressed
	ch = _getch();

	if(ch == 'a')
		std::cout << "You pressed a!" << std::endl;
	else
		std::cout << "You did not press a!" << std::endl;

	return 0;
}
Last edited on Jun 28, 2012 at 7:41pm
Jun 28, 2012 at 8:01pm
Thanks a lot! It worked great :D
Jun 29, 2012 at 7:59pm
Glad I could help :)
Jun 30, 2012 at 2:42pm
If you want to do it with out pressing enter, you could use GetAsyncKeyState() might be lowercase s.
1
2
3
4
if (GetAsyncKeyState(0x43))
{
        Code here
}


That should be for a. It is in hexidecimal.
Topic archived. No new replies allowed.