Click here to Skip to main content
6,291,124 members and growing! (16,088 online)
Email Password   helpLost your password?
Web Development » Trace and Logs » Debug and Tracing     Intermediate

Console Enhancements

By Wesner Moise

This article enhances console support in .NET such as clearing, colored text, and more; enables console support in Windows apps as well as DOS apps; and also eases testing and debugging of .NET applications.
C#.NET 1.0, .NET 1.1, Win2K, WinXP, Win2003, Visual Studio, Dev
Posted:28 Jun 2003
Updated:2 Jul 2003
Views:173,693
Bookmarked:110 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
96 votes for this article.
Popularity: 9.62 Rating: 4.85 out of 5

1

2
1 vote, 1.0%
3
12 votes, 12.5%
4
83 votes, 86.5%
5

Introduction

System.Console is a class provided by the framework to handle console I/O and redirection. The Win32 API also supports a set of console APIs. Win32 supports a single console for each application (process), even a Windows Forms Application. Consoles support a number of features such as buffering, full-screen mode, colors, and so on. You can call another process and capture its output into your own console. With console applications, the console is inherited from the calling process; however, Windows application are detached from any console.

Unfortunately, the Console class does not take advantage of most of the features supported in the console APIs.  So, I introduced a new class called WinConsole, that provides more of the functionality offered by the Win32 class. It provides some of the more popular console functions, but not yet all of them. It can be used in both Console and Windows Applications and probably Class Libraries as well. I plan to add the full range of functionality sometime in the future.

I initially intended to use it for debugging purposes and was going to call it DebugConsole, but it is also used as a replacement or extension for the existing Console class. I found that testing a low-level UI-less, data structure or class in a full-fledged Windows Application can be very difficult. Standard I/O no longer work. The Debugger Output Window is just a poor substitute for the console. It has fewer capabilities than the console and requires flipping between the application and the debugger. Now, with WinConsole, Console.WriteLine() and Console.ReadLine() are both available for WinForms apps.

Web applications are still out of luck. Sorry.

WinConsole in Console Application

In Console applications, WinConsole provides additional features such as the following:

1) Hiding and showing the console window (WinConsole.Visible = false)
2) Clearing the console window (WinConsole.Clear())
3) Getting or setting the cursor location
4) Changing the color of text to one of 16 different console colors (WinConsole.Color = ConsoleColor.Red)

<Sample image

5) Having standard error output written with a different color as demonstrated above.
6) Automatically flashing window and beeping when an error message is written out. (WinConsole.Beep())
7) Capturing asserts and traces to standard error each with a different color scheme

To read input and write output, you can use Console.WriteLine and Console.ReadLine. You can also use WinConsole.WriteLine or WinConsole.ReadLine, but it always defers to the Console functions.

 

WinConsole in Windows Application

WinConsole truly shines in a Windows application environment. It enables the use of an additional console window alongside the main application window, which can be hidden and shown anytime. It contains all the additional enhancements, listed above for Console applications, and more.

WinConsole is especially useful for debugging and tracing. Testing data structures becomes a lot harder when moving from a console app to a windows application, because of the omission of console window to report interesting messages. The standard Debug.Write, Trace.Write call OutputDebugString, which sends data to the limited Debugger's output window.

With WinConsole, calls from Debug.Write(Line), Trace.Write(Line), and even Console.Write(Line) and Console.Error.Write(Line) can output to the application console window, each in its own independent color. In addition to coloring, there is a flashing mode that can be selected (flash once, flash until response) to alert the developer/tester to warning and error messages.

Input can also be read from the console window through Console.Read(Line). This allows the application to easily receive input from the user in a simple synchronous model instead of a more complex event-driven model. In this way, an entire command-line system can be developed for the application while it is running for performing various tests.

The best part is that the console window is owned and painted separately by the operating system in a separate thread, so that it is always viewable while debugging even after entering break mode or flipping back and forth between the debugger and the application. In contrast, normal application windows are frozen--they cannot be redrawn since event processing is suspended after a break.

WinConsole API

To use the WinConsole in a Windows application, WinConsole.Visible should be assigned at some point before the console is used. Of course, the assignment needs to be true in order to see any contents. Alternatively, WinConsole.Initialize() can be called, but the console may not be visible.

In console applications, WinConsole.Initialize() is sufficient. Most of the properties and methods in WinConsole will cause an initialization to occur as well, if it has not already occurred.

Below is a list of properties.

Properties Description
Buffer (IntPtr) Get the current Win32 buffer handle
BufferSize (Coord) Returns the size of buffer
Color (ConsoleColor) Gets or sets the current text and background color and other attributes of text
CtrlBreakPressed (bool) indicates whether control break was pressed. Value is automatically cleared after reading.
CursorPosition (Coord) Gets and sets the current position of the cursor
Handle (IntPtr) Get the HWND of the console window
MaximumScreenSize (Coord) Returns the maximum size of the screen given the desktop dimensions
ParentHandle Gets and sets a new parent hwnd to the console window
ScreenSize (Coord) Returns a coordinates of visible window of the buffer
Title Gets or sets the title of the console window
Visible Specifies whether the console window should be visible or hidden

To change the color of text, Color must be assigned a ConsoleColor.

ConsoleColor is an enum consist of flags Red, Blue, Green, Intensified, RedBG, BlueBG, GreenBG, IntensifiedBG. The BG colors are for the background color. By using various combinations of each color flags, you can achieve 16 colors for text and 16 colors for the background. To produce white, Red|Green|Blue|Intensified must be set. When the intensified flag is missing, the unintensified color is midway between black and the chosen color. So, white becomes gray, red becomes dark red, and so on.

Below is a list of properties.

Method Description
Beep() Produces a simple beep
Clear() Clear the console window
Flash(bool) Flashes the console window (Currently now working on my machine, if you can figure out why, I would be grateful)
GetWindowPosition(out int x, out int y, out int width, out int height) Gets the Console Window location and size in pixels
Initialize() Initializes WinConsole -- should be called at the start of the program using it
LaunchNotepadDialog(string arguments)  
RedirectDebugOutput(bool clear, ConsoleColor color, bool beep) Redirects debug output to the console
clear - clear all other listeners first
color - color to use for display debug output
RedirectTraceOutput(bool clear, ConsoleColor color)
Redirects trace output to the console
SetWindowPosition(int x, int y, int width, int height) Sets the console window location and size in pixels

In addition to these methods and properties, WinConsole also includes all the standard Console methods and properties, which it simply redirects to the Console class, so that there is exactly no difference between calling a Console method and its corresponding WinConsole method. For example, WinConsole.WriteLine calls Console.WriteLine.

Coloring Standard Error Output, Debug Output or Trace Output

I have also included a ConsoleWriter class, which can be used to provided colored output, flashing, and/or beeping to the console window.

ConsoleWriter is constructed by calling new on the ConsoleWriter(TextWriter writer, ConsoleColor color, ConsoleFlashingMode mode, bool beep) constructor.

Redirecting Standard Error:
Console.Error = new ConsoleWriter(Console.Error, ConsoleColor.Red|ConsoleColor.Intensified, 0, true);

Redirecting Debug or Trace Output:
Debug.Listeners.Remove("default"); // Debug.Listeners.Clear();
Debug.Listeners.Add( new TextWriterTraceListener( new ConsoleWriter(Console.Error, ...) ) );

You can also use the convenience function: WinConsole.RedirectDebugOutput(...).

Launch Notepad Dialog

At Microsoft, virtually every group uses a command-line environment for building, testing and so on; this can sometimes make it difficult to get a complex set of information from a user, because of the UI-less environment.

Thus, the infamous notepad dialog was invented. A command would start a notepad.exe with a filename argument and wait for it to exit. The file is prepopulated with help comments and default information. The user edits the file and indicates OK by exiting notepad. The suspended command, which was waiting for notepad to exit, is now resumed and ready to process the notepad file.

The image shows a typical notepad dialog.

Sample image

WinConsole.LaunchNotepadDialog takes a filename argument, and launches a notepad dialog, in which the user can modified the specified file.

Conclusion

This represents just one of my articles in the debugging series. There will be others.

I'd appreciate your vote; it is a powerful motivating force for me.

Version History

  • June 28, 2003 - Original article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Wesner Moise


Member
I was former employee at Microsoft from 1994-2000. I was hired by Microsoft upon graduating from Harvard College, where I studied Applied Math and Computer Science. I co-developed Microsoft Excel (versions 97-XP) during that period. I left to pursue MBA studies in California for the next two years. I am currently starting a company called SoftPerson specializing in software applications, enhanced with Artificial Intelligence. I keep a blog as http://wesnerm.blogs.com/net_undocumented/ which I plan to update daily.
Occupation: Web Developer
Location: United States United States

Other popular Trace and Logs articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 61 (Total in Forum: 61) (Refresh)FirstPrevNext
QuestionHow could i scroll the WinConsole window in WinAPP? Pinmemberliaokobe23:01 6 May '08  
AnswerRe: How could i scroll the WinConsole window in WinAPP? PinmemberFiwel10:24 30 Jun '08  
AnswerRe: How could i scroll the WinConsole window in WinAPP? PinmemberFiwel10:38 30 Jun '08  
GeneralHow to use Pinmemberaamir ali1:16 6 Nov '07  
GeneralConsole for a Win App started from command line PinmemberBertrand Boichon5:22 13 Sep '06  
GeneralRe: Console for a Win App started from command line PinmemberEverythingsTaken7:18 16 Aug '07  
AnswerRe: Console for a Win App started from command line PinmemberEverythingsTaken16:04 16 Aug '07  
GeneralEnhancement - Activate a buffer by code PinmemberJordi Ceballos5:35 16 Jun '06  
AnswerRe: Enhancement - Activate a buffer by code PinmemberKermittt14:53 18 Oct '06  
QuestionDetect how application was started Pinmembergewe6:20 21 Apr '06  
GeneralEnhancement - How to set the icon for the console window PinmemberBruceN22:13 22 Feb '06  
Generalhow about a .ReadLine(string) that shows the message and exits after any pressed key? PinmemberKelraad23:39 3 Jan '06  
GeneralRe: how about a .ReadLine(string) that shows the message and exits after any pressed key? PinmemberKelraad4:35 4 Jan '06  
GeneralBug In ctrl-break-handler Pinmemberfrankgthw7:42 22 Aug '05  
GeneralClear the screen with attributes Pinmemberfrankgthw7:01 22 Aug '05  
GeneralRe: Clear the screen with attributes PinmemberSimplicio Jison14:29 10 May '06  
GeneralRe: Clear the screen with attributes Pinmemberfrankgthw23:29 10 May '06  
GeneralSince this is so good Pinmemberxlar5412:55 18 Aug '05  
GeneralFlashInfo not passing hwind Pinmembermicrosci17:29 12 May '05  
Generalhow to include in cpp soln Pinmemberamolaggarwal9:00 4 Apr '05  
GeneralMultiple Monitors PinmemberBruceN6:25 11 Dec '04  
GeneralSingle Key From the Keyboard PinmemberEric Frick16:04 27 Apr '04  
GeneralRe: Single Key From the Keyboard PinmemberManiB21:14 17 May '04  
AnswerRe: Single Key From the Keyboard PinmemberSimonChambers5:51 20 Sep '07  
GeneralThanks! PinmemberJoeEspo15:13 16 Mar '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 2 Jul 2003
Editor: Nick Parker
Copyright 2003 by Wesner Moise
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project