Mail Archives: djgpp/1998/10/13/09:46:38
Chris Broome wrote in message ...
>DoctorXV AT aol DOT com wrote in message <4661cac DOT 3622aaa3 AT aol DOT com>...
>>how do I get C++ to detect arrow key presses? I use Turbo C++ 3.0
>
>This works very well in a loop:
>
>#include <conio.h>
>
>/* These are just a few ASCII values for the keys hit.*/
>#define ENTER 13
>#define ESC 27
>#define UP 72
>#define DOWN 80
>#define LEFT 75
>#define RIGHT 77
>#define BACKSPACE 8
>#define TAB 9
>#define SPACE 32
>
>void main()
>{
>char key;
>while(SomeCondition)
> {
> if (kbhit()) /* first detect if the keyboard was hit */
> {
> key=getch(); /* if it was, then get what key was hit */
> if (key==UP) .... /* if up was hit, do something*/
> }
> }
>}
This is very close to right and it does work but the ascii values used
are those of characters. That is to say UP == 'H' == 72 and DOWN == 'P' =
80. The difference between say the user pressing 'P' and the down key is
that getch () first sends a 0 and then the corresponding UP | DOWN | LEFT |
RIGHT value. The reason this above code will work is that kbhit () will
return != 0 when something is in the keyboard buffer, thus the code inside
the if (kbhit ()) {} will exicute twice for the arrow keys. Furthermore,
the user will be able to manipulate the object you wish to move by simply
pressing 'H' | 'P' |...
A better way to do this would be to have your code look something
like...
void main ()
{
// declare all variables
char ch;
.... // what ever you like
do // ensure code inside loop is exicuted at least once, if this is not
desired put the while condition here
{
if (kbhit ()) // if keypressed then interpret it...
{
ch = getch ();
switch (ch)
{
case 'a': // put in whatever code you like
break;
case 'P': // put in whatever code you like
break;
case 0: ch = getch ();
if (ch == UP)
{
// then up key pressed...
}
else if (ch = DOWN)
{
// then down key
pressed...
}
// Note no break here this
is because a 0 isn't only sent for the arrow keys so
// implementing the code
in this manner will allow exicution continue into the
// default portion of the
switch, detecting an invalid keystroke. Only works if the
// case 0 is directly
above the default case....
default: // an invalid key has been
pressed take whatever action you like....
break;
}
}
} while (whatever); // ensure this condition becomes true at some
point...
}
The above code will guarantee the code you wish to exicute on the arrow
commands are only exicuted when the arrow keys are infact pressed. Note
you'll still need the topmost code's includes and defines.
Karl Martens
May the force be with you!! :-)
- Raw text -