NOVICE question: How to know when a key is pressed

Rogue Winter rogue at cellar.UUCP
Sat Apr 13 03:11:27 AEST 1991


etxpihl at tore.ericsson.se (DEE Tomas Pihl) writes:

> I want to know how you can scan if a specific key has been pressed.
> Just as this program I'm using know know that i press eg. ESC.
> I don't want the pressed key to be echoed out to the screen as it is
> with getchar().
> 
I'm amazed.  I can actually ANSWER a question here!

There are two functions in Microsoft C (I'm not sure if they're ANSI or MS 
defined) called getch() and getche() that you may find useful.

getchar() does not just echo the character to the screen.  getchar() uses the 
computer's character buffer to store and pass characters.  Useful for 
full-word commands, but a horror when you need single-key response.  The 
getch() and getche() functionsbypass the character buffer and offer an 
immediate response.

The difference is that getch() will not echo characters to the screen (your 
desired effect), while getche() will (you may not want it now, but you may in 
the future).  The syntax, like getchar() is:

        ch = getch()

To use getch() and getche(), you need to #include <conio.h> (console i/o) in 
your preprocessor commands.

rogue winter     : "Never trust a gentleman any further than you can throw
rogue at cellar.uucp: his valet."



More information about the Comp.lang.c mailing list