Press any key to continue…

Sometimes I do remember nostalgically, how in my early high-school days, I was quite thrilled on discovering the INKEY$ function in GWBASIC, which allowed me to implement a “Press any key to continue…” feature for my program. It somehow made my little GWBASIC programs seem more professional and cool.

10 PRINT "hello"
20 WHILE INKEY$=""
30 WEND
40 PRINT "bye"
50 END

Of course later on when I moved over to C/C++, the “Press any key…” functionality ceased to excite me any more because getch and getche were pretty commonly used CRT functions and it was no biggie to use them in my programs. I had very nearly forgotten about my adventures with “Press any key…” until the advent of .NET when I was stunned to realize that there was no managed way for me to incorporate a “Press any key…” feature for my console applications. I could use Console::Read or Console::ReadLine, but these functions waited till I pressed the [Return] key which was wholly unacceptable for my purposes.

Guess what? The Whidbey BCL has a Console::ReadKey(...) method! Woohoo! 😀

You can simply use Console::ReadKey() or you can use the overload that takes a bool parameter; you specify true to hide the pressed key and false to display the pressed key. The parameter-less ReadKey will display the pressed key, and internally it simply calls the other overload passing false as argument.

The ReadKey method returns a ConsoleKeyInfo object that can be used to examine the key/key-combination that was pressed. For example you can do fancy console stuff like this :-

Console::WriteLine(
    "Press Alt-F12 to exit, else keep looping like mad...");
while(true)
{
    ConsoleKeyInfo cki = Console::ReadKey(true);
    if(cki.Key == ConsoleKey::F12 &&
          cki.Modifiers == ConsoleModifiers::Alt)
        break;
}

A Ctrl-Break or a Ctrl-C will still break into the program though. For those interested, internally ReadKey calls the ReadConsoleInput and related Win32 API functions.

So now I can happily implement my “Press any key to continue…” feature and beam with pride at my really professional looking program 😉

Advertisements

3 thoughts on “Press any key to continue…

  1. This indeed a good old memory, but is there a way to implement it in C# 2003 for ver1.1?
    For my understanding the ReadKey commmand is refer to framework ver2.0.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s