Unleash the Console

.NET 1.0 introduced the Console class to give programmers a convenient way to build simple command-line applications. The first version of the Console was fairly rudimentary, with little more than basic methods like Write( ), WriteLine( ), Read( ), and ReadLine( ). In .NET 2.0, new features have been added, allowing you to clear the window, change foreground and background colors, alter the size of the window, and handle special keys.

Note

At last, a Console class with keyboard-handling and screen-writing features.

How do I do that?

The best way to learn the new features is to see them in action. Example 6-7 shows a simple application, ConsoleTest, which lets the user move a happy face character around a console window, leaving a trail in its wake. The application intercepts each key press, checks if an arrow key was pressed, and ensures that the user doesn't move outside of the bounds of the window.

Warning

In order for the advanced console features to work, you must disable the Quick Console window. The Quick Console is a console window that appears in the design environment, and it's too lightweight to support features like reading keys, setting colors, and copying characters. To disable it, select Tools → Options, make sure the "Show all settings checkbox" is checked, and select the Debugging → General tab. Then, turn off the "Redirect all console output to the Quick Console window."

Example 6-7. Advanced keyboard handling with the console

Module ConsoleTest ...

Get Visual Basic 2005: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.