Modifying text in the console using Visual Basic

孤者浪人 提交于 2021-02-08 04:01:33

问题


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

and as events occur I want to increment that 0.

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.

Thanks in advance.


回答1:


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.

There are slightly different ways to do this in VB vs. C#.

  • VB: Use the vbCr code.

  • C#: Use the \r code.

Here's some sample 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);
}  


来源:https://stackoverflow.com/questions/15371146/modifying-text-in-the-console-using-visual-basic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!