繁体   English   中英

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

[英]How Can I change the background color of a text on a Console Application C#

我在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);

这就是我想要实现的目标

这就是它的样子

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#控制台颜色教程此页面提供了更改控制台应用程序颜色所需的全部内容。

    Console.BackgroundColor = ConsoleColor.Blue;
    Console.ForegroundColor = ConsoleColor.White;
    Console.WriteLine("White on blue.");
    Console.WriteLine("Another line.");

上面的代码将更改控制台的背景和前景色。

这会有所帮助

        for (int i = 0; i < 100; i++)
        {
            Console.WriteLine();
            string Text = "MAP" + i;
            Console.SetCursorPosition((Console.WindowWidth - Text.Length) / 2, Console.CursorTop);
            if (i == 0)
            {
                Console.BackgroundColor = ConsoleColor.White;
                Console.ForegroundColor = ConsoleColor.Black;                    
                Console.WriteLine(Text);
                Console.ResetColor();
            }
            else
            {
                Console.WriteLine(Text);
            }
        }

看到 结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM