Home
VB.NET
Console.ReadKey Example
Updated 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.
Console.WriteLine
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
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 7, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen