Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep text at the top of console?

Tags:

c#

.net

console

I'm trying to have my console application automatically scroll but keep the text at the top. The text history must be accessible so Console.Clear isn't viable.

Is there any method to detect when console scrolls or any method to adjust the current Y pos, as I know console will scroll when your text is about to be off-screen. I'd like this same effect, but to keep the newest line at the top of the window. Any help is appreciated, thank you!

like image 543
Joshua Avatar asked Oct 27 '25 03:10

Joshua


1 Answers

You may use the Console.SetWindowPosition() method. *

Parameters
left Int32
The column position of the upper left corner of the console window.

top Int32
The row position of the upper left corner of the console window.

Here's an example to demonstrate:

static void Main(string[] args)
{
    int i = 0;
    while (true)
    {
        Console.ReadKey(false);
        Console.WriteLine($"You are currently at line #{++i}");
        Console.SetWindowPosition(0, i - 1);
    }
}

Result:

Scroll Console to Top

Note that if you're getting close to the value of Console.BufferHeight, you could get an ArgumentOutOfRangeException, that is, when the new position (top) is greater than Console.BufferHeight - Console.WindowHeight, so you might want to take that into account. I would add a simple condition to handle this case. Example:

int newTop = i - 1;
if (newTop + Console.WindowHeight <= Console.BufferHeight)
{
    Console.SetWindowPosition(0, newTop);
}

..but you might want to handle this differently (e.g., increase the buffer as you go, change the window size, etc.)


* Don't be mislead by the name of the method. A "window" here doesn't mean the actual desktop/console window in OS terms (borders, etc.). Instead, it refers to the currently displayed window of the character buffer. To move the actual console window, you'd have to use the SetWindowPos Windows API function. Example.

like image 68
41686d6564 stands w. Palestine Avatar answered Oct 28 '25 16:10

41686d6564 stands w. Palestine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!