如何更新 C# Windows 控制台应用程序中的当前行? [英] How can I update the current line in a C# Windows Console App?

查看:18
本文介绍了如何更新 C# Windows 控制台应用程序中的当前行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中构建 Windows 控制台应用程序时,是否可以写入控制台而无需扩展当前行或转到新行?例如,如果我想显示一个百分比来表示一个进程与完成的接近程度,我只想更新光标所在行上的值,而不必将每个百分比都放在一个新行上.

这可以通过标准"C# 控制台应用程序完成吗?

解决方案

如果你只打印 " " 到控制台光标会回到当前行的开头然后你可以重写它.这应该可以解决问题:

for(int i = 0; i <100; ++i){Console.Write("
{0}% ", i);}

注意数字后面的几个空格,以确保删除之前的所有内容.
还要注意使用 Write() 而不是 WriteLine() 因为您不想在行尾添加 ".

When building a Windows Console App in C#, is it possible to write to the console without having to extend a current line or go to a new line? For example, if I want to show a percentage representing how close a process is to completion, I'd just like to update the value on the same line as the cursor, and not have to put each percentage on a new line.

Can this be done with a "standard" C# console app?

解决方案

If you print only " " to the console the cursor goes back to the beginning of the current line and then you can rewrite it. This should do the trick:

for(int i = 0; i < 100; ++i)
{
    Console.Write("
{0}%   ", i);
}

Notice the few spaces after the number to make sure that whatever was there before is erased.
Also notice the use of Write() instead of WriteLine() since you don't want to add an " " at the end of the line.

这篇关于如何更新 C# Windows 控制台应用程序中的当前行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆