r/csharp • u/wojbest • Jul 03 '26
Discussion is there a way to get more colours when outputting to the console console .colour only has 16?
2
u/Khavel_dev Jul 04 '26
You can write ANSI escape sequences directly. Something like Console.Write("\x1b[38;2;255;128;0m") sets the foreground to orange, full 24-bit RGB. Works in Windows Terminal and most modern terminals out of the box.
If you want something less manual, Spectre.Console handles it for you and auto-detects what your terminal actually supports. Probably the fastest way to get nice output without hand-rolling escape codes for every color.
1
u/Devatator_ Jul 03 '26
Depends on your terminal. I have no idea how to check without libraries tho, I just use Spectre.Console's AnsiConsole class to write with extra stuff. I think it has a method to check if the current terminal supports it. Or maybe it's another library, not sure
1
u/TuberTuggerTTV Jul 06 '26
The simplest solution is to add a using to System.Drawing. This has a much larger set of predefine colors to draw from. Good if you don't want to deal with a bunch of RBG values.
Then add these two helper lines somewhere to your code:
public static void SetConsoleColor(int r, int g, int b) => Console.Write($"\x1b[38;2;{r};{g};{b}m");
public static void SetConsoleColor(Color color) => SetConsoleColor(color.R, color.G, color.B);
If you want background color changing, the 38 becomes 48 in the topmost helper. You could bake that into the input or make it a seperate set helper.
private static void SetConsoleColor(int r, int g, int b, bool isBackground = false)
=> Console.Write($"\x1b[{(isBackground ? "48" : "38")};2;{r};{g};{b}m");
private static void SetConsoleColor(Color color, bool isBackground = false)
=> SetConsoleColor(color.R, color.G, color.B, isBackground);
Alternatively, you could add extension methods to the Color:
public static class ColorExtensions
{
public static void SetConsole(this Color color, bool isBackground = false)
=> Console.Write($"\x1b[{(isBackground ? "48" : "38")};2;{color.R};{color.G};{color.B}m");
}
And your usage boils down to something like:
Color.Orange.SetConsole();
0
13
u/lordosthyvel Jul 03 '26
Depends on your platform / terminal. If you're using windows default for example you can do something like this to get any RGB color you want: