c#在控制台輸出彩色文字的方法

來源:互聯網
上載者:User

“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。前者取得控制台的控制代碼,後者設定控制台的文字顏色。

迴圈語句中將字串的每個字元設定為不同的顏色,逐一顯示出來,最終成為一串彩色的文字。

至於代碼的實際用途嗎,我想在控制台上輸出日誌的時候可能會有作用。尤其是要醒目地顯示不同類型日誌的場合下,比如可以將錯誤,警告和資訊類型的日誌分別用紅色,黃色與通常的白色區別開來。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.