代码之家  ›  专栏  ›  技术社区  ›  pradeeptp

使用console在同一位置写入字符串。在C 2.0中写入

  •  26
  • pradeeptp  · 技术社区  · 17 年前

    我在C 2.0中有一个控制台应用程序项目,需要在一个while循环中将一些内容写入屏幕。我不希望屏幕滚动,因为使用console.write或console.writeline方法将不断在控制台屏幕上递增显示文本,从而开始滚动。

    我想把绳子写在同一个位置。我该怎么做?

    谢谢

    2 回复  |  直到 7 年前
        1
  •  50
  •   Jon Skeet    17 年前

    使用 Console.SetCursorPosition 设置位置。如果需要先确定,请使用 Console.CursorLeft Console.CursorTop 性质。

        2
  •  1
  •   fishjd Adam Gent    7 年前

    函数来写入循环的进度。循环计数器可以用作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) {
                }
            }
        }
    
    推荐文章