C# cmd中修改显示(显示进度变化效果)

好多人想在运行或者调试含有大量数据或者比较慢C#程序的时候能够显示自己的程序完成的程度,这里有一个方法能发不断地修改cmd的同一行,以达到显示完成百分比的目的

public void PrintPercentage(int FinishedCount, int TotalCount)  
{
decimal finishedPercentage = Convert.ToDecimal(FinishedCount) / Convert.ToDecimal(TotalCount);
Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.WriteLine((finishedPercentage * 100).ToString("f1") + "%");
}

 

其中SetCursorPosition的目的就是重置光标到,里面参数的含义是(left, top),当前cmd最下面一行即为top.ToString("f1")是指保留一位小数.

或者用“\r”也能达到目的,表示将光标回到当前第一行,如下:

public void PrintPercentage(int FinishedCount, int TotalCount)  
{
decimal finishedPercentage = Convert.ToDecimal(FinishedCount) / Convert.ToDecimal(TotalCount);
Console.WriteLine("\r" + (finishedPercentage * 100).ToString("f1") + "%");
}

 

相比之下前一种更加灵活一点,可以定位到任何位置

posted @ 2011-10-30 20:39  伍浩铖  阅读(2215)  评论(0编辑  收藏  举报