45

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.

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

Thanks

Pavel Chuchuva
  • 22,633
  • 10
  • 99
  • 115
pradeeptp
  • 2,131
  • 6
  • 29
  • 39

2 Answers2

69

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 22
    Works a treat, if you have already "written" a line you can just keep doing `Console.SetCursorPosition(0, Console.CursorTop - 1); Console.WriteLine(progress);` to "update the same line from the start... – Paul Kohler Jul 14 '14 at 06:15
4

Function to write the progress of a loop. Your loop counter can be used 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(origCol, origRow);
            } catch (ArgumentOutOfRangeException e) {
            }
        }
    }
fishjd
  • 1,617
  • 1
  • 18
  • 31