C# 可以让用户输入设置控制台颜色吗?
C# Possible To Have User Input Set Console Colors?
我创建了一个简单的控制台游戏并且很高兴结果如何所以只是做了一些最后的调整我想既然我为背景和文本设置了控制台颜色,我可以让用户选择颜色吗?我知道这可能是一堆蠕虫,但现在我试过了,它不会让我设置以下内容,我至少想知道这是否可能。这是我尝试过的。
Console.WriteLine("\nPlease enter desired background color for this screen: ");
var screen = Console.ReadLine();
Console.WriteLine("\nPlease enter desired text color for this screen: ");
var text = Console.ReadLine();
Console.BackgroundColor = ConsoleColor.screen;
Console.ForegroundColor = ConsoleColor.text;
VS 给出的错误是 ConsoleColor 不包含屏幕和文本的定义。
感谢海登让我走上正轨,想出了这个:
Console.WriteLine("\nPlease enter desired background color for this screen: ");
string back = Console.ReadLine();
Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), back, true);
您收到错误的原因是 ConsoleColor.screen
和 ConsoleColor.text
不存在(这与 screen
和 text
不同).
为了实现用户想要改变控制台颜色,您可以尝试以下方法:
Console.WriteLine("\nPlease enter desired background color for this screen: ");
var screen = Console.ReadLine();
Console.WriteLine("\nPlease enter desired text color for this screen: ");
var text = Console.ReadLine();
// Attempt to parse the colors that the user entered into their respective enum values.
// The new values of background and foreground will be set to the user input
if(Enum.TryParse(screen, out ConsoleColor background))
{
Console.BackgroundColor = background;
}
if (Enum.TryParse(text, out ConsoleColor foreground))
{
Console.ForegroundColor = foreground;
}
我创建了一个简单的控制台游戏并且很高兴结果如何所以只是做了一些最后的调整我想既然我为背景和文本设置了控制台颜色,我可以让用户选择颜色吗?我知道这可能是一堆蠕虫,但现在我试过了,它不会让我设置以下内容,我至少想知道这是否可能。这是我尝试过的。
Console.WriteLine("\nPlease enter desired background color for this screen: ");
var screen = Console.ReadLine();
Console.WriteLine("\nPlease enter desired text color for this screen: ");
var text = Console.ReadLine();
Console.BackgroundColor = ConsoleColor.screen;
Console.ForegroundColor = ConsoleColor.text;
VS 给出的错误是 ConsoleColor 不包含屏幕和文本的定义。
感谢海登让我走上正轨,想出了这个:
Console.WriteLine("\nPlease enter desired background color for this screen: ");
string back = Console.ReadLine();
Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), back, true);
您收到错误的原因是 ConsoleColor.screen
和 ConsoleColor.text
不存在(这与 screen
和 text
不同).
为了实现用户想要改变控制台颜色,您可以尝试以下方法:
Console.WriteLine("\nPlease enter desired background color for this screen: ");
var screen = Console.ReadLine();
Console.WriteLine("\nPlease enter desired text color for this screen: ");
var text = Console.ReadLine();
// Attempt to parse the colors that the user entered into their respective enum values.
// The new values of background and foreground will be set to the user input
if(Enum.TryParse(screen, out ConsoleColor background))
{
Console.BackgroundColor = background;
}
if (Enum.TryParse(text, out ConsoleColor foreground))
{
Console.ForegroundColor = foreground;
}