Welcome Guest!
Create Account | Login
Locator+ Code:

FTPOnline Channels Conferences Resources Hot Topics Partner Sites Magazines About FTP RSS 2.0 Feed

Click here to receive your FREE subscription to Visual Studio Magazine

email article
printer friendly
get the code
more resources

Spice Up Console Apps
by Bill McCarthy and Brian Noyes

Q: Make Console.Read()Return From Any Key
It's great that VB.NET makes writing console apps so easy compared to VB6, but I find limitations in what I can do. I want my application to respond as the user presses any key. I've tried using Console.Read(), but it doesn't seem to return unless the user presses the Enter key only. Is this a bug, or do I need to do something else? Also, can I change the color of the text in the console window?

Technology Toolbox

A: .NET's Console class is simply a wrapper for the Win32 API. You can write your own wrapper class in VB6 or VB.NET that extends and enhances this basic functionality, but you can't inherit from the .NET Console class because it's sealed. You must write a separate class instead.

Some of the API calls are reasonably straightforward. Set or get the console window's caption, for example, by creating a Text property in your class that simply calls the Win32 API functions SetConsoleTitle and GetConsoleTitle, respectively.

Figure 1. Console Text Never Looked So Good.

Getting and setting the console text forecolor and backcolor is a little more complex (see Figure 1). You must specify both forecolor and backcolor even if you want to set only one of them. This requirement doesn't match typical object-property-to-single-field coding practices, but you can work around that by retrieving the colors in the Property Get and calling on that Property Get in the other color's Property Let/Set (this works for both VB6 and VB.NET). You retrieve the colors by calling the GetConsoleScreenBufferInfo API and returning the wAttributes member, which is a 16-bit integer value. The forecolor value is stored in the integer's lower four bits (&H0 to &HF), and the backcolor value is stored in the next four bits (&H10 to &HF0). The code for setting and retrieving the console colors is based in part on code posted by Mattias Sjögren to the public newsgroups.

Back to top

Printer-Friendly Version

Java Pro | Visual Studio Magazine | Windows Server System Magazine
.NET Magazine | Enterprise Architect | XML & Web Services Magazine
VSLive! | Thunder Lizard Events | Discussions | Newsletters | FTPOnline Home