gpt4 book ai didi

c# - 如何更改控制台应用程序 C# 上文本的背景颜色

转载 作者:太空宇宙 更新时间:2023-11-03 22:55:40 24 4
gpt4 key购买 nike

我正在用 C# 编写一个小型控制台应用程序,我想使用箭头键在我的菜单中导航。为了使所选选项对用户可见,我想用白色背景和黑色文本突出显示它,但只突出显示单词而不是整行。

我试图将光标定位在单词的开头,这样只有单词会突出显示,但它不起作用。有人可以告诉我正确的方向吗?

for (int i = 0; i < filesArray.Length; i++)
{
Console.WriteLine();

if (i == 0)
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
Program.WriteAtTheMiddleOfTheScreen(filesArray[0]);
Console.ResetColor();
}
else
{

Program.WriteAtTheMiddleOfTheScreen(filesArray[i]);
}
}

Console.WriteLine();
Program.WriteAtTheMiddleOfTheScreen("Exit Program");

Console.SetCursorPosition((Console.WindowWidth/2)-filesArray[0].Length+2, 2);

That is what I want to achieve

That is how it looks like

public static void WriteAtTheMiddleOfTheScreen(string message)
{
message = String.Format("{0," + ((Console.WindowWidth / 2) + (message.Length / 2)) + "}", message);
Console.WriteLine(message);
}

最佳答案

Console 类支持两个属性,分别是ForegroundColorBackgroundColor

参见 MSDN: System.Console.ForegroundColorMSDN: System.Console.BackgroundColor

(提示:使用 Microsoft Visual Studio,您可以将光标放在 Console 上并按 Ctrl+Space 以获取 Console 提供的所有属性的列表.)

您可以使用 System.ConsoleColor 枚举的成员设置这些属性,该枚举包含 WhiteBlue 等成员。

参见 MSDN: System.ConsoleColor

因此,您将 BackgroundColor 属性设置为某种颜色,执行 System.Console.Write(),然后将 BackgroundColor 设置为某种颜色其他,依此类推。

请记住,空间是用背景颜色绘制的,因此要防止屏幕区域被绘制为不需要的背景颜色,请不要将 BackgroundColor 属性设置为不需要的值并写入空格那里。

关于c# - 如何更改控制台应用程序 C# 上文本的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45502040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com