c#在控制台输出彩色文字的方法
时间:2021-07-17 03:46:51
“Hello World!”的程序写过不少,不过都是在黑色背景的控制台上显示白色的文字。这次决定写点特别的,让“Hello World!”变成彩色的文字。
示例代码如下:
using System;
using System.Runtime.InteropServices;
[assembly:CLSCompliant(true)]
namespace ColorConsole
{
public sealed class HelloWorld
{
private HelloWorld() { }
public static void Main()
{
const UInt32 STD_OUTPUT_HANDLE = unchecked((UInt32)(-11));
IntPtr consoleHandle = NativeMethods.GetStdHandle(STD_OUTPUT_HANDLE);
string s = "Hello World!";
for (int i = 0; i < s.Length; i++)
{
NativeMethods.SetConsoleTextAttribute(consoleHandle, (ushort)(i + 1));
Console.Write(s[i]);
}
Console.ReadLine();
}
}
class NativeMethods
{
private NativeMethods() { }
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr GetStdHandle(UInt32 type);
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.U1)]
public static extern bool SetConsoleTextAttribute(IntPtr consoleHandle, ushort attributes);
}
}
主要用到的方法是GetStdHandle与SetConsoleTextAttribute。前者取得控制台的句柄,后者设置控制台的文字颜色。
循环语句中将字符串的每个字符设置为不同的颜色,逐一显示出来,最终成为一串彩色的文字。
至于代码的实际用途吗,我想在控制台上输出日志的时候可能会有作用。尤其是要醒目地显示不同类型日志的场合下,比如可以将错误,警告和信息类型的日志分别用红色,黄色与通常的白色区别开来。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
java内部类的定义与分类示例详解
Java实战之基于swing的QQ邮件收发功能实现
Java 中的 clone( ) 和 new哪个效率更高
![](https://img.aspxhome.com/file/2023/6/59326_0s.png)
C#实现查杀本地与远程进程的方法
Unity使用LineRender断笔写字
![](https://img.aspxhome.com/file/2023/0/86950_0s.png)
Java的Swing编程中使用SwingWorker线程模式及顶层容器
Java编程实现对十六进制字符串异或运算代码示例
![](https://img.aspxhome.com/file/2023/2/58892_0s.png)
Logback 使用TurboFilter实现日志级别等内容的动态修改操作
Android开发中使用颜色矩阵改变图片颜色,透明度及亮度的方法
![](https://img.aspxhome.com/file/2023/6/90126_0s.jpg)
Spring Boot教程之必须了解的核心概念
![](https://img.aspxhome.com/file/2023/2/70582_0s.png)
详解Spring Cloud Gateway修改请求和响应body的内容
![](https://img.aspxhome.com/file/2023/1/91051_0s.png)
C# 使用鼠标点击对Chart控件实现数据提示效果
![](https://img.aspxhome.com/file/2023/0/104230_0s.webp)
Android常用的图片加载库
![](https://img.aspxhome.com/file/2023/8/90168_0s.gif)
C#中重载重写和覆盖的定义与区别
我用java实现了王者荣耀的皮肤和英雄技能
![](https://img.aspxhome.com/file/2023/1/63491_0s.png)
Javacsv实现Java读写csv文件
Java安全-ClassLoader
![](https://img.aspxhome.com/file/2023/9/80329_0s.png)
SpringCloud Alibaba项目实战之nacos-server服务搭建过程
![](https://img.aspxhome.com/file/2023/2/85542_0s.jpg)
C#数据导入到EXCEL的方法
Java实现有限状态机的推荐方案分享
![](https://img.aspxhome.com/file/2023/9/77989_0s.png)