NullifyNetwork

The blog and home page of Simon Soanes
Skip to content
[ Log On ]

Just a handy little method I chucked together that might be useful when prototyping stuff in command line applications:

/// <summary>
/// Draw a progress bar at the current cursor position.
/// Be careful not to Console.WriteLine or anything whilst using this to show progress!
/// </summary>
/// <param name="progress">The position of the bar</param>
/// <param name="total">The amount it counts</param>

private static void drawTextProgressBar(int progress, int total)
{
 //draw empty progress bar
 Console.CursorLeft = 0;
 Console.Write("["); //start
 Console.CursorLeft = 32;
 Console.Write("]"); //end
 Console.CursorLeft = 1;
 float onechunk = 30.0f / total;
 
 //draw filled part
 int position = 1;
 for (int i = 0; i < onechunk * progress; i++)
 {
  Console.BackgroundColor = ConsoleColor.Gray;
  Console.CursorLeft = position++;
  Console.Write(" ");
 }

 //draw unfilled part
 for (int i = position; i <= 31; i++)
 {
  Console.BackgroundColor = ConsoleColor.Black;
  Console.CursorLeft = position++;
  Console.Write(" ");
 }

 //draw totals
 Console.CursorLeft = 35;
 Console.BackgroundColor = ConsoleColor.Black;
 Console.Write(progress.ToString() + " of " + total.ToString()+"    "); //blanks at the end remove any excess
}

Permalink  2 Comments 

Very good! by thes at 11/21/2007 14:50:43
Just copy&pasted and it worked! Thanks a lot ;-)

One change by Edelbrock at 03/10/2009 17:06:42
Only change I would make would be to make the qualifer greater than or equal to. It fills that last spot. Great logic otherwise.