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

前端 未结 2 2033
天命终不由人
天命终不由人 2020-11-29 07:56

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

相关标签:
2条回答
  • 2020-11-29 08:46

    Use Console.SetCursorPosition to set the position. If you need to determine it first, use the Console.CursorLeft and Console.CursorTop properties.

    0 讨论(0)
  • 2020-11-29 08:50

    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.

        /// <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) {
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题