While programming my first C# console applications I missed functions to read the console-keycode without waiting for the pressed key. As a C++ programmer I searched for functions like
_getch(). But I only found functions like
Console.ReadLine(). Both are still waiting until a key is pressed. But I do not want to wait. I searched on the CODE PROJECT for the keywords (
GetKey) to get a quickly solution. But unfortunately I get no single hit!!! So I had to solve it on my own. And here is my solution.
I build a C++ Class Library with the necessary classes and functions in it. I named it ConsoleLibrary because there are a couple of functions that are useful for an C# console application. After that I created four C# console applications demos that referenced the ConsoleLibrary, to show you how to manage the new functions.
This is an example for a keyboard-test, using the ConsoleLibrary.
This is an example for a display-test, using the ConsoleLibrary.
This is an example for showing an ASCII-table, using the ConsoleLibrary.
This is an example for programming a game (SNAKE), using the ConsoleLibrary.
Using the code
There are two kinds of using the ConsoleLibrary functions. First of them is to insert the ConsoleLibrary project in your solution file. After that you can make an direct reference in your console application project to the ConsoleLibrary. In this case your are able to debug into the ConsoleLibrary sourcecode, and you can make changes in it.
The second way to use the ConsoleLibrary functions is to make an reference to the ConsoleLibrary.dll. Use this way when you don't want to make changes anyway.
In both cases don't forget the
Then you can directly use the functions in your sourcecode. Here are some examples:
To flush the keyboard buffer:
To check the keycode in a loop:
key = Keyboard.GetKey();
if (key != (int)KeyCode.KeyNone)
if (key == (int)KeyCode.KeyF1)
Console.WriteLine("You've pressed F1.");
} while (key!=(int)KeyCode.KeyEscape);
To set the caption:
To clear the screen:
To set fore- and background color:
To show or hide the cursor
To set the cursor-position
There are also other functions available. Please have a look in the sourcecode of the ConsoleLibrary.
Points of Interest
With this ConsoleLibrary I was able to transfer my first posted article Einstein's riddle solved in C++ from C++ to C#. If you're interested in this C# sourcecode please give me a hint.
I hope my ConsoleLibrary is also useful for you. If so, I'm happy and wish you kind regards...
- 13.05.2004 Submit this article