Share via


About Align Text In Console Window

Question

Friday, May 29, 2009 6:39 PM

well i've been searching a lot in the internet and i still can't find a way to center text in the console window
i've already added color and bg color but the align its too complicated for me

i hope some one can help me

thanks to all

Yours Zdat~

All replies (3)

Friday, May 29, 2009 6:44 PM ✅Answered

Assuming you are using String objects, String.Format has various ways to handle padding (via which you can achieve alignment).

See http://www.csharp-examples.net/align-string-with-spaces/ for an example.http://blog.voidnish.com


Friday, May 29, 2009 6:45 PM ✅Answered

You can't perfectly center the text, because the text may be an odd number of characters, and the window width may be an even number.  Nevertheless, here's two version of the same thing, that both center text.  They both add spaces to the front of your string to format it for the width of the console.

static string Center(string input)

{

    return input.PadLeft(((Console.WindowWidth - input.Length) / 2) + input.Length);

}

 

static string Center(string input)

{

    return new String(' ', (Console.WindowWidth - input.Length) / 2) + input;
}    

David Morton - http://blog.davemorton.net/ - @davidmmorton


Friday, May 29, 2009 6:49 PM ✅Answered

using System;
class Program
{
    static void Main(string[] args)
    {
        string hello = "Hello, World!";
        Console.SetCursorPosition(Console.WindowWidth/2 - hello.Length/2, Console.WindowHeight/2);
        Console.WriteLine(hello);
    }
}