C# 控制台程序(命令行程序)設置字體顏色,窗口寬高,光標行數


控制台程序(命令行程序)設置窗口寬度高度,如下代碼:

            Console.WriteLine(Console.WindowHeight);
            Console.WriteLine(Console.BufferHeight);
            Console.ReadKey();
            Console.Title = "Test";//設置窗口標題
            Console.WindowWidth = 120;
            Console.BufferHeight = 1000;
            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();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM