我有一个控制台应用程序,它运行一个任务,报告它的完成百分比.在执行此操作时,我会向控制台显示一个进度条.我在调用Console.Write
之前使用Console.SetCursorPosition(0, Console.CursorTop);
来更新当前行,这样进度条就会相应地更新.
当我使用Windows终端在PowerShell中运行它时,它的行为恰好是我想要的.每次更新都会覆盖当前行.问题是,如果我在(传统的)conhost.exe中从PowerShell运行应用程序,它不会覆盖该行.输出为:
[ ][ 0%]
[= ][ 1%]
[= ][ 2%]
...诸若此类.下面是一个完整的程序,展示了这种行为:
static void Main(string[] args)
{
Progress<int> progress = new Progress<int>();
progress.ProgressChanged += Progress_ProgressChanged;
IProgress<int> reporter = progress;
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
reporter.Report(i);
}
}
private static void Progress_ProgressChanged(object? sender, int e)
{
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(GetProgressString(e));
}
private static string GetProgressString(int progress)
{
// Total width of the progress meter.
// Console width minus "[][100%]".
int width = Console.WindowWidth - 8;
double progressDec = (double)progress / 100;
int numChars = (int)(progressDec * width);
StringBuilder meterBuilder = new StringBuilder();
for (int i = 0; i < numChars; i++)
{
meterBuilder.Append('=');
}
for (int i = 0; i < (width - numChars); i++)
{
meterBuilder.Append(' ');
}
return $"[{meterBuilder}][{string.Format("{0, 3}", progress)}%]";
}
有没有其他方法可以在旧的Windows控制台主机上实现这一点?