前言
在DOS下,爲了顯示一些進度信息,使用C#在.net core 3.1下編寫了一個類ControlProcessBar類,用於顯示進度信息。基本原理是通過 Console.CursorLeft
和 Console.CursorTop
進行定位,通過 Console.BackgroundColor
和 Console.ForegroundColor
進行顏色設置。
實際效果
調用方式
ControlProcessBar
的用法很簡單,只有一個 Percent
屬性,其值範圍爲 [0, 1]
,具體用法如下所示。
static void Main(string[] args)
{
Random rnd = new Random();
ConsoleBar cb = new ConsoleBar();
while (cb.Percent < 1)
{
// 使用時只要修改 Percent 這個屬性即可自動更新。
cb.Percent += rnd.NextDouble() * 0.01;
Thread.Sleep(10);
}
}
源代碼
using System;
namespace ConsoleApp1
{
class ConsoleProcessBar
{
public int Top { get; set; }
public int Left { get; set; }
public int Length { get; set; } = 80;
double percent = 0;
public double Percent
{
get => percent;
set
{
if (percent == value)
return;
percent = value;
Update();
}
}
public ConsoleColor BackColor { get; set; } = ConsoleColor.Blue;
public ConsoleColor ForeColor { get; set; } = ConsoleColor.White;
void show(string s)
{
Console.Write(s);
}
public ConsoleBar()
{
Left = Console.CursorLeft;
Top = Console.CursorTop;
Console.SetCursorPosition(Left, Top);
Console.WriteLine(new string('*', Length));
for (int i = 0; i < Length; i++)
{
show(" ");
}
Console.WriteLine();
Console.WriteLine(new string('*', Length));
}
public ConsoleBar(int left = 0, int top = 0)
{
Left = left;
Top = top;
Console.SetCursorPosition(Left, Top);
Console.WriteLine(new string('*', Length));
for (int i = 0; i < Length; i++)
{
show(" ");
}
Console.WriteLine();
Console.WriteLine(new string('*', Length));
}
public void Update()
{
Percent = Percent > 1 ? 1 : Percent;
Percent = Percent < 0 ? 0 : Percent;
Console.SetCursorPosition(Left, Top + 1);
ConsoleColor backColor = Console.BackgroundColor;
ConsoleColor foreColor = Console.ForegroundColor;
Console.BackgroundColor = BackColor;
Console.ForegroundColor = ForeColor;
int max = (int)(Percent * Length);
for (int i = 0; i < max; i++)
{
show(" ");
}
Console.BackgroundColor = backColor;
Console.ForegroundColor = foreColor;
int x = Console.CursorLeft;
int y = Console.CursorTop;
Console.SetCursorPosition(Left + 35, Top);
Console.Write(" " + Percent.ToString("P") + " ");
Console.SetCursorPosition(x, y);
Console.WriteLine();
}
}
}