Learning VB.NET: Working with Variables, Conditionals, and Console Input - Reading Console Input
(Page 2 of 4 )
So far, we've used the console for output, but our game, of course, needs to be able to accept input from the user. Now that we know how to work with variables, we can start tackling input. As with output, the Console class is used for input. With output, we started with the WriteLine procedure, and with input, we'll start with ReadLine. Whereas WriteLine writes a complete line to the console, ReadLine reads a complete line from the console (that is, the user). The input is then stored in a string. Here's ReadLine in action:
Dim input As String = Console.ReadLine()
Console.WriteLine(input)
The first line of the above snippet reads a line of input from the user, and the second line writes the line back out to the user.
ReadLine will work fine for many purposes. For example, we might ask the user his name, which he'll type in and then press enter. However, ReadLine is not appropriate for input because not all input will be in line format. For example, when the user wants to move around, he'll press an arrow key. We'll then need to intercept the pressed key and treat it as an individual key rather than a line. For situations like this, we'll need to use the ReadKey function, which reads an individual key from the console and then returns information about the key in the form of a ConsoleKeyInfo object. Here's a basic example of ReadKey:
Dim input As ConsoleKeyInfo = Console.ReadKey()
Our ConsoleKeyInfo object has a number of properties that describe the key pressed. One property is the KeyChar property, which will return the character representation of the key pressed:
Console.WriteLine("You pressed the '{0}' key.", input.KeyChar)
However, this property has some limitations. ReadKey will not only read basic alphanumeric keys, but it will also read other keys, such as function keys, that do not have appropriate character representations. For example, try running the above two lines of code and then pressing the F1 key.
The next property of a ConsoleKeyInfo object is Key. The Key property will return a value from the ConsoleKey enumeration. This enumeration contains values for all of the keys. So, to check which key has been pressed, one would simply need to compare the value in Key with the values in the ConsoleKey enumeration. To do this, however, we need to take a look at conditionals.
Next: Conditionals >>
More Visual Basic.NET Articles
More By Peyton McCullough