C# 控制台应用程序中的自定义颜色
在 C# 控制台应用程序中,自定义默认控制台颜色之外的字体颜色的能力是一项很有价值的功能。不幸的是,可用颜色列表有限,缺少所需的橙色。
自定义颜色的可用选项
虽然提供的颜色列表是官方支持的颜色集通过控制台,有一种方法可以实现自定义颜色:
以编程方式更改控制台颜色
选择方法后对于自定义颜色支持,您可以在 C# 中实现颜色更改程序:
外部库方法:
PINVOKE 方法:
使用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中文网其他相关文章!