I am having a problem with centering text in a C#.NET4 console app.
This is my method for centering the text:
private static void centerText(String text)
{
int winWidth = (Console.WindowWidth / 2);
Console.WriteLine(String.Format("{0,"+winWidth+"}", text));
}
However, I just get the output as it would have been outputted normally. If I however use this line:
Console.WriteLine(String.Format("{0,"+winWidth+"}", "text"));
The "text" gets centered as it should.
I am calling centerText
with these two methods:
private static void drawStars()
{
centerText("*********************************************");
}
private static void title(string location)
{
drawStars();
centerText("+++ Du er nu her: " + location + "! +++");
drawStars();
}
Try this instead:
The problem with your initial code was that your text starts in the screen center. You want the center of the text to be there.
You're going to do a bit more work if you want to print entire paragraphs centered like this.
I have my own method for calling console headers:
Then you call it like this
YourStaticClass.Header("Test", "Version 1.0");
it should look like this:
You can replace the
90
inwindowsWidth
withConsole.WindowWidth
UPDATE - February 2019 - code cleaned and made dynamic size
The text passed in may have whitespace such as
\r\n
, then remove that before calling the write such as