在 C# 2.0 中使用 Console.Write 在同一位置写入字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/283669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 21:35:31  来源:igfitidea点击:

Writing string at the same position using Console.Write in C# 2.0

c#.net

提问by pradeeptp

I have a console application project in C# 2.0 that needs to write something to the screen in a while loop. I do not want the screen to scroll because using Console.Write or Console.Writeline method will keep displaying text on console screen incremently and thus it starts scrolling.

我在 C# 2.0 中有一个控制台应用程序项目,需要在 while 循环中向屏幕写入一些内容。我不希望屏幕滚动,因为使用 Console.Write 或 Console.Writeline 方法将继续在控制台屏幕上递增显示文本,因此它开始滚动。

I want to have the string written at the same position. How can i do this?

我想让字符串写在相同的位置。我怎样才能做到这一点?

Thanks

谢谢

采纳答案by Jon Skeet

Use Console.SetCursorPositionto set the position. If you need to determine it first, use the Console.CursorLeftand Console.CursorTopproperties.

使用Console.SetCursorPosition设置位置。如果您需要先确定它,请使用Console.CursorLeftConsole.CursorTop属性。

回答by fishjd

Function to write the progress of a loop. Your loop counter can be uses as the x position parameter. This prints on line 1, modify for your needs.

写入循环进度的函数。您的循环计数器可以用作 x 位置参数。这打印在第 1 行,根据您的需要进行修改。

    /// <summary>
    /// Writes a string at the x position, y position = 1;
    /// Tries to catch all exceptions, will not throw any exceptions.  
    /// </summary>
    /// <param name="s">String to print usually "*" or "@"</param>
    /// <param name="x">The x postion,  This is modulo divided by the window.width, 
    /// which allows large numbers, ie feel free to call with large loop counters</param>
    protected static void WriteProgress(string s, int x) {
        int origRow = Console.CursorTop;
        int origCol = Console.CursorLeft;
        // Console.WindowWidth = 10;  // this works. 
        int width = Console.WindowWidth;
        x = x % width;
        try {
            Console.SetCursorPosition(x, 1);
            Console.Write(s);
        } catch (ArgumentOutOfRangeException e) {

        } finally {
            try {
                Console.SetCursorPosition(origRow, origCol);
            } catch (ArgumentOutOfRangeException e) {
            }
        }
    }