1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <windows.h>
char pressanykey( const char *prompt )
{
DWORD mode;
HANDLE hstdin;
INPUT_RECORD inrec;
DWORD count;
char default_prompt[] = "press the 'any' key...";
char result = '\0';
/* Set the console mode to no-echo, raw input, */
/* and no window or mouse events. */
hstdin = GetStdHandle( STD_INPUT_HANDLE );
if (hstdin == INVALID_HANDLE_VALUE
|| !GetConsoleMode( hstdin, &mode )
|| !SetConsoleMode( hstdin, 0 ))
return result;
if (!prompt) prompt = default_prompt;
/* Instruct the user */
WriteConsole(
GetStdHandle( STD_OUTPUT_HANDLE ),
prompt,
lstrlen( prompt ),
&count,
NULL
);
FlushConsoleInputBuffer( hstdin );
/* Wait for and get a single key PRESS */
do ReadConsoleInput( hstdin, &inrec, 1, &count );
while ((inrec.EventType != KEY_EVENT) || !inrec.Event.KeyEvent.bKeyDown);
/* Remember which key the user pressed */
result = inrec.Event.KeyEvent.uChar.AsciiChar;
/* Wait for and get a single key RELEASE */
do ReadConsoleInput( hstdin, &inrec, 1, &count );
while ((inrec.EventType != KEY_EVENT) || inrec.Event.KeyEvent.bKeyDown);
/* Restore the original console mode */
SetConsoleMode( hstdin, mode );
return result;
}
const char* messages[ 3 ] =
{
"Press the 'any' key...",
"\n\rAck! Not that one! Try again.",
"\n\rWoah! Watch it! Press the ANY key!"
};
int main()
{
int i;
char keys[ 4 ];
for (i = 0; i < 3; i++)
keys[ i ] = toupper( pressanykey( messages[ i ] ) );
keys[ 3 ] = '\0';
if (strcmp( keys, "ANY" ) == 0)
printf( "\nFinally! Thank you.\n" );
else
printf( "\nOh forget it!\n" );
printf( "\n\n\n\n\n" );
pressanykey( "Press any key to quit. (Seriously this time.)" );
return 0;
}
|