经常使用控制台来写小玩意,总希望有个进度条,各种百度,终于简单实现:
先上进度条帮助类:
public class ConsoleProgress
{
static ConsoleProgress consoleProgress = new ConsoleProgress();
int top=0;
int end=0;
private ConsoleProgress()
{
top = Console.CursorTop;
}
public static ConsoleProgress Intance
{
get
{
if (consoleProgress == null)
{
lock(new object())
{
consoleProgress = new ConsoleProgress();
}
}
return consoleProgress;
}
}
public void Reset()
{
top =Console. CursorTop;
}
public void ShowProgress(int curvalue,string msg)
{
if (CursorTop > end && end > 0)
{
top = CursorTop;
}
Console.SetCursorPosition(100/2-(msg.Length)/2, top);
//显示提示信息
Console.WriteLine(msg);
Console.SetCursorPosition(100 / 2 - ((curvalue.ToString()+"%").Length) / 2, top+1);
Console.WriteLine("{0}%", curvalue);
Console.SetCursorPosition(CursorLeft, top+2);
Console.WriteLine("┃");
Console.SetCursorPosition(CursorLeft+1, top+2);
Console.WriteLine(new string('*',curvalue));
if (curvalue >= 100)
{
Console.SetCursorPosition(curvalue+1, top + 2);
Console.WriteLine("┃");
Console.SetCursorPosition(100/2-("操作已完成".Length/2) + 1, top + 3);
Console.WriteLine("操作已完成");
}
end= Console.CursorTop;
}
}
2.接下来是调用:
Console.WriteLine("开始进度条控制");
for (int i = 0; i++ < 100;) {
ConsoleProgress.Intance.ShowProgress(i, "正则测试");
Thread.Sleep(50);
}
ConsoleProgress.Intance.Reset();//此处用于开启一个新的进度条,如果不调用此句,则需要有Console.WriteLine()方法被调用后方可正常在用showProgress,否则进度控制会保留上一次调用时的位置:
// Console.WriteLine("再次测试。。。。。。。。。。。");
for (int i = 0; i++ < 100;)
{
ConsoleProgress.Intance.ShowProgress(i, "正则测试");
Thread.Sleep(50);
}
Console.ReadLine();
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
贴出新方法,减小进度条的大小!
public void ShowProgress(int curvalue,string msg)
{
int total = 30;
if (CursorTop > end && end > 0)
{
top = CursorTop;
}
Console.SetCursorPosition(30 / 2-(msg.Length)/2, top);
//显示提示信息
Console.WriteLine(msg);
Console.SetCursorPosition(30 / 2 - ((curvalue.ToString()+"%").Length) / 2, top+1);
Console.WriteLine("{0}%", curvalue);
Console.SetCursorPosition(CursorLeft, top+2);
Console.WriteLine("┃");
Console.SetCursorPosition(CursorLeft+1, top+2);
Console.WriteLine(new string('*',curvalue*30/100));
if (curvalue >= 30)
{
Console.SetCursorPosition(curvalue*30/100+1, top + 2);
Console.WriteLine("┃");
Console.SetCursorPosition(30 / 2-("操作已完成".Length/2) + 1, top + 3);
Console.WriteLine("操作已完成");
}
end= Console.CursorTop;
}