C# 控制台程序(命令行程序)设置字体颜色,窗口宽高,光标行数

时间:2022-07-09 02:26:10

控制台程序(命令行程序)设置窗口宽度高度,如下代码:

            Console.WriteLine(Console.WindowHeight);
Console.WriteLine(Console.BufferHeight);
Console.ReadKey();
Console.Title = "Test";//设置窗口标题
Console.WindowWidth = ;
Console.BufferHeight = ;
Console.WriteLine(Console.WindowWidth);
Console.WriteLine(Console.WindowHeight);
Console.WriteLine("---------------------");
Console.WriteLine(Console.BufferWidth);
Console.WriteLine(Console.BufferHeight);

设置窗口字体颜色和背景颜色:

            Console.BackgroundColor = ConsoleColor.Blue; //设置背景色
Console.ForegroundColor = ConsoleColor.White; //设置前景色,即字体颜色
Console.WriteLine("第一行白蓝.");
Console.ResetColor(); //将控制台的前景色和背景色设为默认值
Console.BackgroundColor = ConsoleColor.Green;
Console.ForegroundColor = ConsoleColor.DarkGreen;
string str = "第三行 绿暗绿";
Console.WriteLine(str.PadRight(Console.BufferWidth - (str.Length % Console.BufferWidth))); //设置一整行的背景色
Console.ResetColor();

//显示出console中支持的背景色及前景色

static void ShowColor()
        {
            Type type = typeof(ConsoleColor);
            Console.ForegroundColor = ConsoleColor.White;
            foreach (string name in Enum.GetNames(type))
            {
                Console.BackgroundColor = (ConsoleColor)Enum.Parse(type, name);
                Console.WriteLine(name);
            }

Console.BackgroundColor = ConsoleColor.Black;
            foreach (string name in Enum.GetNames(type))
            {
                Console.ForegroundColor = (ConsoleColor)Enum.Parse(type, name);
                Console.WriteLine(name);
            }

foreach (string bc in Enum.GetNames(type))
            {
                Console.BackgroundColor = (ConsoleColor)Enum.Parse(type, bc);
                foreach (string fc in Enum.GetNames(type))
                {
                    Console.ForegroundColor = (ConsoleColor)Enum.Parse(type, fc);
                    Console.WriteLine("bc="+bc+",fc="+fc);
                }
                Console.WriteLine();
            }
        }

计算当前光标所在的行数,针对于Console.BufferHeight的值,代码如下:

            ShowColor();
int m = Console.CursorTop;//查看当前行号Console.BufferHeight
ShowColor();
int n = Console.CursorTop;
ShowColor();
int o = Console.CursorTop;
Console.ReadKey();