C# 控制台應用程式中的自訂顏色
在C# 控制台應用程式中,自訂預設控制台顏色之外的字體顏色的能力是一項很有價值的功能。不幸的是,可用顏色清單有限,缺少所需的橙色。
自訂顏色的可用選項
雖然提供的顏色清單是官方支援的顏色集通過控制台,有一種方法可以實現自訂顏色:
以編程方式更改控制台顏色
選擇方法後對於自定義顏色支持,您可以在 C#中實作顏色變更程序:
外部函式庫方法:
使用PINVOKE的具體實作
提供的程式碼片段示範如何使用PINVOKE方法設定自訂顏色,包括橙色:using System; using System.Drawing; using System.Runtime.InteropServices; public class CustomConsoleColors { [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetConsoleScreenBufferInfoEx(IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFO_EX csbe); [StructLayout(LayoutKind.Sequential)] private struct COORD { public short X; public short Y; } [StructLayout(LayoutKind.Sequential)] private struct SMALL_RECT { public short Left; public short Top; public short Right; public short Bottom; } [StructLayout(LayoutKind.Sequential)] private struct CONSOLE_SCREEN_BUFFER_INFO_EX { public int cbSize; public COORD dwSize; public COORD dwCursorPosition; public ushort wAttributes; public SMALL_RECT srWindow; public COORD dwMaximumWindowSize; public ushort wPopupAttributes; public bool bFullscreenSupported; public uint black; public uint darkBlue; public uint darkGreen; public uint darkCyan; public uint darkRed; public uint darkMagenta; public uint darkYellow; public uint gray; public uint darkGray; public uint blue; public uint green; public uint cyan; public uint red; public uint magenta; public uint yellow; public uint white; } public static void SetColor(ConsoleColor color, Color targetColor) { CONSOLE_SCREEN_BUFFER_INFO_EX csbe = new CONSOLE_SCREEN_BUFFER_INFO_EX(); csbe.cbSize = Marshal.SizeOf(csbe); IntPtr hConsoleOutput = GetStdHandle(-11); if (hConsoleOutput == new IntPtr(-1)) throw new Exception("Error retrieving console buffer handle"); if (!GetConsoleScreenBufferInfoEx(hConsoleOutput, ref csbe)) throw new Exception("Error retrieving console buffer info"); switch (color) { case ConsoleColor.Black: csbe.black = ColorTranslator.ToWin32(targetColor); break; case ConsoleColor.DarkBlue: csbe.darkBlue = ColorTranslator.ToWin32(targetColor); break; // ... (similar code for other colors) case ConsoleColor.DarkYellow: csbe.darkYellow = ColorTranslator.ToWin32(targetColor); break; case ConsoleColor.Gray: csbe.gray = ColorTranslator.ToWin32(targetColor); break; // ... (similar code for other colors) case ConsoleColor.White: csbe.white = ColorTranslator.ToWin32(targetColor); break; } if (!SetConsoleScreenBufferInfoEx(hConsoleOutput, ref csbe)) throw new Exception("Error setting console buffer info"); } public static void Main() { SetColor(ConsoleColor.DarkYellow, Color.Orange); Console.WriteLine("Custom orange color applied!"); Console.ReadLine(); } }透過使用此方法,您可以將任何所需的顏色(包括橙色)設定為控制台的前景色或背景色,從而在C# 控制台應用程式中提供更豐富且可自訂的使用者體驗。
以上是如何將自訂顏色(例如橙色)添加到我的 C# 控制台應用程式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!