Is it possible to keep portions of the console from scrolling in .NET?

Figure 1

Figure 1: the bottom portion is to scroll, while the top portion is to stay put.

So I’m writing a CLI .NET Core application.

The top portion of the image is to stay put whereas the bottom portion is to scroll under the top portion.

If there was a more direct access to the console, it would be rather easy. But as we are in C#, no such (cross-platform) access exists that I am aware of.

So, how would I achieve the desired goal here, without platform-locking?

Answer

You can try this if it might give you an idea. Based on this post C# Console : How to make the console stop scrolling automatically?.

static readonly int maxLine = 10;
static int currentLine = 0;

static void Main(string[] args)
{
    setHeader();

    while (true)
    {
        writeLine("Please type and enter:");
        string value = Console.ReadLine();
        writeLine($"Your input is: {value}");
        writeLine($"Current Line: {currentLine}");

        if (currentLine > maxLine)
        {
            resetCursorPosition();
            writeLine($"Your input is: {value}");
            writeLine($"Current Line: {currentLine}");
        }
    }
}

private static void writeLine(string value)
{
    Console.WriteLine(value);
    currentLine = currentLine + 1;
}

private static void resetCursorPosition()
{
    Console.Clear();
    Console.SetCursorPosition(0, 0);
    currentLine = 0;

    setHeader();
}

private static void setHeader()
{
    writeLine("----------------------------------------------");
    writeLine("---------------MY CUSTOM HEADER---------------");
    writeLine("----------------------------------------------");
}

Output:
enter image description here

Leave a Reply

Your email address will not be published. Required fields are marked *