因此,我正在尝试编写一个库,以便在控制台中进行一些简单的格式化,因此每次创建项目时我都不必这样做。包含在其中我想制作一个方法,将您输入的字符串放在一个方框中。
这是我的代码:
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);
}
}
这样可行但是如果你输入一个更大的字符串就会出错。 我如何使它成为一个字符串格式如下 无论消息有多大。
* hi *
* world *
答案 0 :(得分:1)
用这些替换中间的6行应该可以解决问题
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);