问题描述
我想知道是否有更有效的方法来修改控制台中的文本.例如:如果我要跟踪已发生的事件数,我将打印
I was wondering if there is a more efficient way of modifying the text in the console. For example: if I am keeping track of the number of events that have occurred, I'll print
0 events have occurred
随着事件的发生,我想将其递增0.
and as events occur I want to increment that 0.
目前,我这样做的方式非常丑陋:使用String或Stringbuilder跟踪打印到控制台的所有内容,如果需要进行任何更改,请更改字符串,清除控制台,然后将字符串打印到控制台.除了效率不高外,它还会以丑陋的方式显示,导致在短时间内进行太多更改时控制台会闪烁".
Currently I am doing that in a very ugly way:Keep track of everything printed to the console using a String or Stringbuilder and if I need to make any changes, change the string, clear the console, print the string to the console. Aside from probably not being very efficient, it displays in an ugly way resulting in the console's "blinking" when too many changes are made in a short period of time.
先谢谢了.
推荐答案
诀窍是使用回车代码.基本上,这会将光标返回到同一行的开头.这与回车+换行符(vbCrLf)不同,后者将光标置于下一行的开头.
The trick is to use the carriage return code. This basically returns the cursor to the beginning of the same line. This is different from the carriage return + line feed (vbCrLf), which puts the cursor at the beginning of the next line.
在VB和C#中,执行此操作的方式略有不同.
There are slightly different ways to do this in VB vs. C#.
-
VB:使用vbCr代码.
VB: Use the vbCr code.
C#:使用\ r代码.
C#: Use the \r code.
以下是一些示例代码:
VB:
For i = 1 To 100
Console.Write("Processing...{0}% complete " & vbCr, i)
System.Threading.Thread.Sleep(100)
Next
C#:
for (int i = 1; i <= 100; i++)
{
Console.Write("Processing... {0}% complete\r", i);
System.Threading.Thread.Sleep(100);
}
这篇关于使用Visual Basic在控制台中修改文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!