Center multiple lines of text in console

94 views Asked by At

I am having a problem. I am making a TUI program. Everything is fine except the fact that I don't like the UI. So I am trying to center my texts to make it seem better. But I am not able to no matter what!

I tried something like this:

string s = "Hello World!";
Console.SetCursorPosition((Console.WindowWidth - s.Length) / 2, Console.CursorTop);
Console.WriteLine(s);

BUT this does not work when I have multiple lines. For example,

string s = "Hello World!\nHey this is another line!";
Console.SetCursorPosition((Console.WindowWidth - s.Length) / 2, Console.CursorTop);
Console.WriteLine(s);
1

There are 1 answers

0
Karen Payne On

See if these work for you, one starts at top of screen while the other centers horizontally and vertically.

internal partial class Program
{
    static void Main(string[] args)
    {
        ConsoleHelpers.CenterLines("Hello world","Enjoy the ride");
        Console.ReadLine();
    }
}

public class ConsoleHelpers
{
    /// <summary>
    /// Center lines horizontally and vertically 
    /// </summary>
    public static void CenterLines(params string[] lines)
    {

        int verticalStart = (Console.WindowHeight - lines.Length) / 2;
        int verticalPosition = verticalStart;

        foreach (var line in lines)
        {
            int horizontalStart = (Console.WindowWidth - line.Length) / 2;
            Console.SetCursorPosition(horizontalStart, verticalPosition);
            Console.Write(line);
            ++verticalPosition;
        }
    }
    /// <summary>
    /// Center lines vertically starting at top of screen
    /// </summary>
    public static void CenterLinesFromTop(params string[] lines)
    {

        int verticalPosition = 0;

        foreach (var line in lines)
        {
            int horizontalStart = (Console.WindowWidth - line.Length) / 2;
            Console.SetCursorPosition(horizontalStart, verticalPosition);
            Console.Write(line);
            ++verticalPosition;
        }
    }
}