Console.ReadKey Example
This page was last reviewed on Nov 7, 2023.
Dot Net Perls
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.
Example. Using ReadKey is significantly more complex than just calling ReadLine. It involves testing the ConsoleKey Enum, as well as properties like KeyChar.
Step 1 We call Console.ReadKey and store the result in a local variable called info. This is a ConsoleKeyInfo.
Step 2 First we test for the escape key. We use an if-statement and test Key against ConsoleKey.Escape.
If Then
Step 3 We call Console.ReadKey again. If we want to test against a char, like the lowercase letter "a," we can access the KeyChar property.
Step 4 We can access the Modifiers property, and test against 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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 7, 2023 (new).
© 2007-2024 Sam Allen.