delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/10/13/12:01:18

Message-ID: <36237742.3B41776A@montana.com>
Date: Tue, 13 Oct 1998 09:52:34 -0600
From: bowman <bowman AT montana DOT com>
X-Mailer: Mozilla 4.5b2 [en] (Win95; I)
X-Accept-Language: en
MIME-Version: 1.0
To: djgpp AT delorie DOT com
Subject: Re: Detecting Arrow key presses
References: <4661cac DOT 3622aaa3 AT aol DOT com> <JVBU1.609$Ni2 DOT 121742 AT news DOT cwix DOT com>
Reply-To: djgpp AT delorie DOT com

Chris Broome wrote:
> 
> >how do I get C++ to detect arrow key presses? I use Turbo C++ 3.0
> 
> This works very well in a loop:
> 
> void main()

int main(void)  would be the preferred usage.

> char key;

getch returns an int, so it would be better if key were an int.

>         key=getch();    /* if it was, then get what key was hit */
>         if (key==UP) ....  /* if up was hit, do something*/

for the extended characters such as the arrow keys, the first call to
getch will return 0. an additional call is needed to get the actual key
code. In this case, the next iteration of the loop will get the keycode,
but there would be no way to differentiate between the up arrow and 'H'
for instance.
One possibility is to indicate the extended characters by setting bit8.


/* ------------   getchx.c --------------------------  */

#include <stdio.h>
#include <conio.h>

int main(void)
{
    int key;

    while ('q' != (key = getchx()))
	if (key)
	     printf("key = %x\n", key)
    return 0;
}

int getchx(void)
{
    int key = 0;
    if (kbhit())
    	if (!(key = getch()))
	     key = getch() | 0x100;
    return key;
}

/* this will return 0x0048 for 'H', 0x0148 for the up arrow, and 0x0000
if no key was available.  */

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019