“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。前者取得控制台的控制代碼,後者設定控制台的文字顏色。
迴圈語句中將字串的每個字元設定為不同的顏色,逐一顯示出來,最終成為一串彩色的文字。
至於代碼的實際用途嗎,我想在控制台上輸出日誌的時候可能會有作用。尤其是要醒目地顯示不同類型日誌的場合下,比如可以將錯誤,警告和資訊類型的日誌分別用紅色,黃色與通常的白色區別開來。