progress in a console window… and it works in 1.x too

BradA did a post for progress in a console window awhile back with a C# sample using one of the new Whidbey API’s in the Console class – Console.SetCursorPosition.  That’s great, but as any tty user should be able to tell you, the simplest method for getting your cursor back a character isn’t explicitly setting the position (like Brad does) or using \r to carriage-return back to the start of the current line and then print the same line with the last character changed (like one of the comments says), but it’s instead \b (aka ^H (do those jokes make more sense now?), ascii 8, etc.) which will quite nicely back up a single character.  KISS, ya know.

I added a Thread.Sleep in the Main loop (so you can actually see it) and took out the ctor for the spinner class (it was useless, might as well let the compiler generate the ctor if it’s going to only do that).  It keeps an index into an array of chars now instead of a switch statement, so it’ll be easier to change which characters you want to use for your particular spinner (the comments on his blog post show others have their own preferences).

using System;
using 
System.Threading;

class Program
{
    
static void Main(string[] args)
    {
        ConsoleSpinner spin 
= new ConsoleSpinner();
        
Console.Write(“Working…. “);
        while 
(true)
        {
            spin.Turn()
;
            
Thread.Sleep(1000);
        
}
    }
}

public class ConsoleSpinner
{
    
int index 0;
    static readonly char
[] spinChars = new char[] {
            
‘/’‘-‘‘\\’‘-‘,
        }
;

    public void Turn()
    {
        Console.Write(
‘\b’);
        
Console.Write(spinChars[index]);
        
index (index + 1) % spinChars.Length;
    
}
}

Advertisements