Reputation: 311
So I am trying to write a library for some easy formatting in console so I don't have to do this everytime i make a project. Included in this I wanted to make a method that puts the string you entered in a box.
This is my code:
public static void DrawBox(string message, char borderChar, ConsoleColor messageColor, ConsoleColor borderColor, int padTop, int padBottom)
{
for (int i = 0; i < Console.WindowWidth; i++)
{
Console.ForegroundColor = borderColor;
Console.Write(borderChar);
}
for (int i = 0; i < padTop; i++)
{
Console.Write(string.Format("{0,0}" + "{0," + (Console.WindowWidth - 1) + "}",borderChar));
}
Console.ForegroundColor = borderColor;
Console.Write(string.Format("{0,0}", borderChar));
Console.ForegroundColor = messageColor;
Console.Write("{0," + ((Console.WindowWidth / 2) + message.Length / 2) + "}", message);
Console.ForegroundColor = borderColor;
Console.Write("{0," + (((Console.WindowWidth / 5) + message.Length / 5)) + "}", borderChar);
for (int i = 0; i < padBottom; i++)
{
Console.WriteLine(string.Format("{0,0}" + "{0," + (Console.WindowWidth - 1) + "}", borderChar));
}
for (int i = 0; i < Console.WindowWidth; i++)
{
Console.ForegroundColor = borderColor;
Console.Write(borderChar);
}
}
This works but if you enter a bigger string it goes wrong. How do i make it so that a string is formatted like this No matter how big the message is.
* hi *
* world *
Upvotes: 2
Views: 139
Reputation: 116
Replacing the 6 lines in the middle with these should do the trick
Console.ForegroundColor = borderColor;
Console.Write("{0,-" + (Console.WindowWidth - message.Length) / 2 + "}", borderChar);
Console.ForegroundColor = messageColor;
Console.Write(message);
Console.ForegroundColor = borderColor;
Console.Write("{0," + ((Console.WindowWidth - message.Length) / 2 + message.Length % 2) + "}", borderChar);
Upvotes: 1