經常使用控制台來寫小玩意,總希望有個進度條,各種百度,終於簡單實現: 先上進度條幫助類: public class ConsoleProgress { static ConsoleProgress consoleProgress = new ConsoleProgress(); int top=0; ...
經常使用控制台來寫小玩意,總希望有個進度條,各種百度,終於簡單實現:
先上進度條幫助類:
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;
}