Keyboard Handling

String Input

The Console.ReadLine() function allows the user to input a string of any length into your application. When they press enter, or an equivalent escape character, a string is returned to the variable that you have assigned to it. The following piece of code is an example of how to fetch a users name and save it into a string.

// Store a user name
string userName = "";
userName = Console.ReadLine();

Character Input

If there is ever a need to read characters individually like in the Basic Console Game tutorial you can use the Console.ReadKey() method. There are some considerations to take into account when using this method.

When you call Console.ReadKey() when the variable Console.KeyAvailable is equal to false, the application will be paused. While if there is a key in the buffer, as indicated by Console.KeyAvailable, the sytem will take the first pressed key from the buffer without pausing the application.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.