#include <iostream>
#include <conio.h>
usingnamespace std;
//----------------------------------------------------------------------------
// The windows stuff turns off the Ctrl-C handler and stuff like that.
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
struct InitConsole
{
DWORD mode;
HANDLE hStdIn;
InitConsole(): hStdIn( GetStdHandle( STD_INPUT_HANDLE ) )
{
GetConsoleMode( hStdIn, &mode );
SetConsoleMode( hStdIn, mode & ~ENABLE_PROCESSED_INPUT );
}
~InitConsole()
{
SetConsoleMode( hStdIn, mode );
}
};
//----------------------------------------------------------------------------
// Extended key handler
// Returns true to ask program to terminate
bool extended_key( int c )
{
switch (c)
{
// Extended key handlers
case 72: cout << "up\n"; break;
case 75: cout << "left\n"; break;
case 77: cout << "right\n"; break;
case 80: cout << "down\n"; break;
// The default handler will just tell you what you pressed
default: cout << "...extended = " << c << "\n"; break;
}
returnfalse;
}
//----------------------------------------------------------------------------
// Normal key handler
// Returns true to ask program to terminate
bool normal_key( int c )
{
switch (c)
{
// Chain to the extended key handler if needed
case 0: case 0xE0:
return extended_key( getch() );
// Quit if user presses 'q' or Ctrl-C
case'q': case'Q': case 3:
cout << "Good-bye!\n";
returntrue;
// Other random stuff
case'a': cout << "a\n"; break;
case'A': cout << "A\n"; break;
case 27: cout << "esc\n"; break;
case 13: cout << "return\n"; break;
// The default handler will just tell you what you pressed
default: cout << "..." << c << "\n"; break;
}
returnfalse;
}
//----------------------------------------------------------------------------
int main()
{
InitConsole _;
cout << "Turn your NumLock off.\n""Press 'q' to quit.\n""Press other keys to see what happens.\n\n";
// Main event loop
while (true)
{
if (kbhit()) // Here's the event -- a key press
if (normal_key( getch() )) // Get the key and pass it to the handler
break;
Sleep( 200 ); // A reasonable pause...
}
return 0;
}
Try pressing Ctrl-[ and see what happens. Then try pressing the Esc key too. What do the two have in common?
Try pressing Alt-F4 and see what doesn't happen. (There is no event handler for it.)
Try pressing Ctrl-C and see what happens. (There is an event handler for it.)