我试图使用字符串更改背景和前景色。
Console.Write("Color:");
string backgroundcolor = Convert.Tostring(Console.ReadLine());
然后背景颜色变成我写的那个
控制台前景色/背景色可以通过 Console.Foreground/BackgroundColor 属性进行设置。
可用的颜色选项在控制台颜色枚举中定义。
我们可以使用 Enum.Parse/TryParse 从字符串值以编程方式设置这些值。
这是一个快速示例程序,它将根据用户的输入设置Console.ForgroundColor
和Console.BackgroundColor
(如果指定的值不是有效的选项,则发出警告(
class Program
{
public static void Warn(string msg)
{
// get current color selections
var currentFGColor = Console.ForegroundColor;
var currentBGColor = Console.BackgroundColor;
// set warning colors
Console.ForegroundColor = ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.Black;
Console.WriteLine($"{msg}");
// set the colors back to the current selections
Console.ForegroundColor = currentFGColor;
Console.BackgroundColor = currentBGColor;
}
static void Main(string[] args)
{
// get foreground input
Console.Write("Foreground Color: ");
string foregroundColorString = Convert.ToString(Console.ReadLine()).Trim();
// get background input
Console.Write("Background Color: ");
string backgroundColorString = Convert.ToString(Console.ReadLine()).Trim();
if (Enum.TryParse(foregroundColorString, ignoreCase: true, out ConsoleColor _foregroundColor))
{
Console.ForegroundColor = _foregroundColor;
}
else
{
Warn("- Invalid ForegroundColor option :(");
}
if (Enum.TryParse(backgroundColorString, ignoreCase: true, out ConsoleColor _backgroundColor))
{
Console.BackgroundColor = _backgroundColor;
}
else
{
Warn("- Invalid BackgroundColor option :(");
}
// output to the console using the requested colors (assuming they were valid)
Console.WriteLine("Hello World!");
Console.ResetColor();
Console.WriteLine("nnPress any key to exit...");
Console.ReadKey();
}
}