C# 控制台程序设置字体颜色 (转)
这几天做了个程序,程序本身很简单。大体功能是输入查询条件,从数据库里取出结果计算并显示。但是用户的要求是使用控制台(console)来实现功能。由于功能简单,程序很快就做完了,在面向用户演示程序时,突然感觉到程序的显示并不友好,全是黑底白字。虽然用户需求的功能演示是成功了,但是显示结果过多时,控制台中的字体颜色看起来非常的不舒服。所以演示完程序后,就准备修改下字体的颜色。从网上搜索了一下,发现在C#中实现很简单,只需要几行代码即可实现。
代码如下:
1 Console.BackgroundColor = ConsoleColor.Blue; //设置背景色 2 Console.ForegroundColor = ConsoleColor.White; //设置前景色,即字体颜色 3 Console.WriteLine(“第一行白蓝.”); 4 Console.ResetColor(); //将控制台的前景色和背景色设为默认值 5 Console.BackgroundColor = ConsoleColor.Green; 6 Console.ForegroundColor = ConsoleColor.DarkGreen; 7 string value = “第三行 绿暗绿”; 8 Console.WriteLine(value.PadRight(Console.WindowWidth-value.Length)); //设置一整行的背景色,.PadRight的语法看下面详解,Console.WindowWidth获取控制台窗口的宽度
关于.PadRight
有时候,为了让格式统一,当位数不足时,给予补足。比如:2008-01-01 13:42:05,这其中就对月、日、秒进行了补位。
在 C# 中可以对字符串使用 PadLeft 和 PadRight 进行轻松地补位。
PadLeft(int totalWidth, char paddingChar) //在字符串左边用 paddingChar 补足 totalWidth 长度,如果没有第二参数,用默认空值补足长度
PadRight(int totalWidth, char paddingChar) //在字符串右边用 paddingChar 补足 totalWidth 长度,如果没有第二参数,用默认空值补足长度
示例:
h = h.PadLeft(2, '0');
注意第二个参数为 char 类型,所以用单引号
参考例子:
1 string Test = "测试下"; 2 Console.Write(Test.PadLeft(Console.WindowWidth - Test.Length, '0'));//Console.WindowWidth获取控制台窗口的宽度 3 Console.ReadKey();//等待键盘动作

浙公网安备 33010602011771号