直接上代码
调用方法
ProgressBar progressBar = new ProgressBar(Console.CursorLeft, Console.CursorTop, 50, ProgressBarType.Multicolor);
Compress(100, progressBar.Dispaly);
Console.WriteLine();
ProgressBar progressBara = new ProgressBar(Console.CursorLeft, Console.CursorTop, 50, ProgressBarType.Character);
Compress(100, progressBara.Dispaly);
Console.WriteLine();
计算方法
public static void Compress(int val, Func<int, int> dispalyProgress = null) {
for (int i = 0; i <=val; i++)
{
if (dispalyProgress != null) {
dispalyProgress(Convert.ToInt32((i / (val * 1.0)) * 100)); }
}
}
打印进度条方法
namespace ProgressBarSolution
{
public enum ProgressBarType
{
Character,
Multicolor
}
public class ProgressBar
{
public int Left {
get; set; }
public int Top {
get; set; }
public int Width {
get; set; }
public int Value {
get; set; }
public ProgressBarType ProgressBarType {
get; set; }
private ConsoleColor colorBack;
private ConsoleColor colorFore;
public ProgressBar() : this(Console.CursorLeft, Console.CursorTop)
{
}
public ProgressBar(int left, int top, int width = 50, ProgressBarType ProgressBarType = ProgressBarType.Multicolor)
{
this.Left = left;
this.Top = top;
this.Width = width;
this.ProgressBarType = ProgressBarType;
Console.SetCursorPosition(Left, Top);
for (int i = left; ++i < Console.WindowWidth;) {
Console.Write(" "); }
if (this.ProgressBarType == ProgressBarType.Multicolor)
{
colorBack = Console.BackgroundColor;
Console.SetCursorPosition(Left, Top);
Console.BackgroundColor = ConsoleColor.DarkCyan;
for (int i = 0; ++i <= width;) {
Console.Write(" "); }
Console.BackgroundColor = colorBack;
}
else
{
Console.SetCursorPosition(left, top);
Console.Write("[");
Console.SetCursorPosition(left + width - 1, top);
Console.Write("]");
}
}
public int Dispaly(int value)
{
return Dispaly(value, null);
}
public int Dispaly(int value, string msg)
{
if (this.Value != value)
{
this.Value = value;
if (this.ProgressBarType == ProgressBarType.Multicolor)
{
colorBack = Console.BackgroundColor;
colorFore = Console.ForegroundColor;
Console.BackgroundColor = ConsoleColor.Yellow;
Console.SetCursorPosition(this.Left, this.Top);
Console.Write(new string(' ', (int)Math.Round(this.Value / (100.0 / this.Width))));
Console.BackgroundColor = colorBack;
Console.ForegroundColor = ConsoleColor.Green;
Console.SetCursorPosition(this.Left + this.Width + 1, this.Top);
if (string.IsNullOrWhiteSpace(msg)) {
Console.Write("{0}%", this.Value); } else {
Console.Write(msg); }
Console.ForegroundColor = colorFore;
}
else
{
Console.SetCursorPosition(this.Left + 1, this.Top);
Console.Write(new string('*', (int)Math.Round(this.Value / (100.0 / (this.Width - 2)))));
Console.SetCursorPosition(this.Left + this.Width + 1, this.Top);
if (string.IsNullOrWhiteSpace(msg)) {
Console.Write("{0}%", this.Value); } else {
Console.Write(msg); }
}
}
return value;
}
}
}