[英]C# Possible To Have User Input Set Console Colors?
I created a simple console game and quite happy how it turned out so just making some final tweaks and i thought since I set the console colors for background and text, could I let the user chose the colors?我创建了一个简单的控制台游戏,结果很高兴,所以只做了一些最后的调整,我想既然我为背景和文本设置了控制台颜色,我可以让用户选择颜色吗? I know it may be a can of worms, but now that I tried and it wont let me set the following, I at least want to know if this is possible.我知道它可能是一罐蠕虫,但现在我尝试过并且它不会让我设置以下内容,我至少想知道这是否可能。 Here is what I tried.这是我尝试过的。
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;
The error VS gives is ConsoleColor does not contain a definition for screen and text. VS 给出的错误是 ConsoleColor 不包含屏幕和文本的定义。
Thanks to Hayden for getting me on the right track, came up with this:感谢海登让我走上正轨,想出了这个:
Console.WriteLine("\nPlease enter desired background color for this screen: ");
string back = Console.ReadLine();
Console.BackgroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), back, true);
The reason that you're receiving the error is due to ConsoleColor.screen
and ConsoleColor.text
doesn't exist (which is not the same as screen
and text
).您收到错误的原因是ConsoleColor.screen
和ConsoleColor.text
不存在(这与screen
和text
)。
To achieve users wanting to change the console colour, you can try the following:要实现用户想要更改控制台颜色,您可以尝试以下操作:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.