Home > database >  Centering Console.WriteLine text in the line
Centering Console.WriteLine text in the line

Time:01-31

I am making a program based on the console. I want to make it look as clean as possible and I want the texts to be centered in their lines.

I tried

string msg = "Hello";

Console.SetCursorPosition((Console.WindowWidth - string.Length) / 2, Console.CursorTop);
Console.WriteLine(msg);

It worked. BUT it doesn't quite solve my problem. You see, I want multiple lines to be centered. For example

string title = "--------Message-------";
Console.SetCursorPosition((Console.WindowWidth - string.Length) / 2, Console.CursorTop);
Console.WriteLine(title);
Console.WriteLine(msg);

Now the entire thing is messed up. I hope someone can give a solution to my issue. Thanks

CodePudding user response:

It is not possible to create Console extension methods, but you may try something like this:

public static class ConsoleExtensions
{
    public static void WriteLineCentered(string msg)
    {
        Console.SetCursorPosition((Console.WindowWidth - msg.Length) / 2, Console.CursorTop);
        Console.WriteLine(msg);
    }
}

And then use this method, when you want to center a text:

string title = "--------Message-------";
string msg = "Hello";
ConsoleExtensions.WriteLineCentered(msg);
ConsoleExtensions.WriteLineCentered(title);

CodePudding user response:

You need to centre each line individually. It's helpful to make a helper function that simply prints out a line of text in the middle of the current line rather than doing it over and over manually.

Of course, that's only going to work for text that fits within a single line - but then again, multi-line text shouldn't really be centred in the first place; that's always going to be awful to look at.

  • Related