Console.ReadKey
This function returns immediately when a key is pressed. We can test the result by storing it in a ConsoleKeyInfo
structure, and testing its properties.
Sometimes, programs written in VB.NET need to be more interactive. Waiting for the Enter key to be pressed can make a program harder to use or more confusing.
Using ReadKey
is significantly more complex than just calling ReadLine
. It involves testing the ConsoleKey
Enum
, as well as properties like KeyChar
.
Console.ReadKey
and store the result in a local variable called info. This is a ConsoleKeyInfo
.if
-statement and test Key against ConsoleKey.Escape
.Console.ReadKey
again. If we want to test against a char
, like the lowercase letter "a," we can access the KeyChar
property.ConsoleModifiers.Control
(or other values) to handle complex key presses.Module Module1 Sub Main() Console.WriteLine("... Press escape, a, then control X") ' Step 1 : call ReadKey, store result in ConsoleKeyInfo. Dim info As ConsoleKeyInfo = Console.ReadKey() ' Step 2: test for escape. If info.Key = ConsoleKey.Escape Then Console.WriteLine("You pressed escape!") End If ' Step 3: call ReadKey, and test KeyChar. info = Console.ReadKey() If info.KeyChar = "a"c Then Console.WriteLine("You pressed a") End If ' Step 4: call ReadKey, and test for Modifiers. info = Console.ReadKey() If info.Key = ConsoleKey.X AndAlso info.Modifiers = ConsoleModifiers.Control Then Console.WriteLine("You pressed control X") End If End Sub End Module... Press escape, a, then control X ?You pressed escape! aYou pressed a ?You pressed control X
Though most VB.NET programs do not need to use Console.ReadKey
, this function is useful for certain highly-interactive programs. It requires testing enums and properties, often in a loop.