Wednesday, September 19, 2012

Console Progress/Status Output and Clear To End Of Line (EOL) (VB.NET)

When writing a .NET Console application, I sometimes have long-running processes for which I like to see status information displayed.  I could simply issue WriteLine statements and have the console window continuously scroll text, but I much prefer information to be displayed and updated in a single location.  Traditionally, what you would do is write some text (of length N) and then write N Ctrl-H characters (Backspace) which moves the cursor back to where it started.  Then when you write again, it overwrites the previous text.  Though, if the new text is shorter than the previous text, you end up with those extra characters – so what you want to do is write your text and then “clear to end of line” (EOL).  I finally got around to implementing that.

There are various ways to tackle this, but I use a couple functions: CONSOLE__WRITE to display text and backspace the cursor to where it started, and CONSOLE__CLEAR_EOL which clears text to the end of the line.  Actually, I incorporated the CONSOLE__CLEAR_EOL as an optional (default True) parameter to CONSOLE__WRITE.

Here are the routines..

    Public Sub CONSOLE__WRITE(ByRef szText As String, Optional ByVal bClearEOL As Boolean = True)
        'Output the text
        'Optionally clear to end of line (EOL)
        If bClearEOL Then CONSOLE__CLEAR_EOL()
        'Move cursor back to where we started, using Backspaces
        Console.Write(Microsoft.VisualBasic.StrDup(szText.Length(), Chr(8)))
    End Sub
    Public Sub CONSOLE__CLEAR_EOL()
        'Clear to End of line (EOL)
        'Save window and cursor positions
        Dim x As Integer = Console.CursorLeft
        Dim y As Integer = Console.CursorTop
        Dim wx As Integer = Console.WindowLeft
        Dim wy As Integer = Console.WindowTop
        'Write spaces until end of buffer width
        Console.Write(Space(Console.BufferWidth - x))
        'Restore window and cursor position
        Console.SetWindowPosition(wx, wy)
        Console.SetCursorPosition(x, y)
    End Sub

Here is a little test program…


Here is a sample of it running..


And when it has completed..


No comments: