#include #include #define SLEEP 100 /* Function prototype for the ctrl signal handler */ BOOL CtrlHandler( DWORD fdwCtrlType ); /* Currently global so we can set it in our ctrl-c handler to cleanly exit */ int exitflag = 0; int main() { HANDLE std_in; DWORD records_read = 0; DWORD i; LPDWORD old_mode; INPUT_RECORD buffer[128]; int sleep_time; /* Number of milliseconds to sleep */ sleep_time = SLEEP; /* Assign a handle to stdinput */ std_in = GetStdHandle(STD_INPUT_HANDLE); if (std_in == INVALID_HANDLE_VALUE) { printf("Could not get handle to stdin\n"); exit(EXIT_FAILURE); } /* Set ourselves able to receive input without a carriage return */ /* Backup the old mode */ if (! GetConsoleMode(std_in, &old_mode) ) { printf("Could not save old screen mode\n"); exit(EXIT_FAILURE); } /* We want to handle ctrl-c and disable all else */ SetConsoleMode(std_in, ENABLE_PROCESSED_INPUT); /* Register for ctrl-c */ if( SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE ) ) { /* Inifite loop - exits via the ctrl-c handler (way below) */ while(!exitflag) { GetNumberOfConsoleInputEvents(std_in, &records_read); if( records_read > 0) { /* We have events */ if( ReadConsoleInput(std_in, buffer, 128,&records_read) ) { for (i = 0; i < records_read; i++) { /* Do something with buffer[i] - print in this case */ if(buffer[i].Event.KeyEvent.bKeyDown) { if(buffer[i].Event.KeyEvent.wVirtualScanCode == 0x1c) { printf("\n"); } else { char c = buffer[i].Event.KeyEvent.uChar.AsciiChar; printf("%c", c); } } } } FlushConsoleInputBuffer(std_in); } else { } /* Preserve our cpu.*/ Sleep(sleep_time); } /* Do our shutdown processing here if need be. */ } else { printf( "\nERROR: Could not set control handler"); } /* Restore the old mode */ SetConsoleMode(std_in, old_mode); return 0; } /* Handle a ctrl event. Coded to handle ctrl-c only. */ BOOL CtrlHandler( DWORD fdwCtrlType ) { switch( fdwCtrlType ) { // Handle the CTRL-C signal. case CTRL_C_EVENT: /* We want to exit cleanly */ exitflag = 1; return( TRUE ); default: return FALSE; } }