What is the best way to convert a System.Drawing.Color to a similar System.ConsoleColor?
+2
A:
Unfortunately, even though the Windows console can support RGB colors, the Console class only exposes the ConsoleColor enumeration which greatly limits the possible colors you can use. If you want a Color structure to be mapped to the "closest" ConsoleColor, that will be tricky.
But if you want the named Color to match a corresponding ConsoleColor you can make a map such as:
var map = new Dictionary<Color, ConsoleColor>();
map[Color.Red] = ConsoleColor.Red;
map[Color.Blue] = ConsoleColor.Blue;
etc...
Or if performance is not that important, you can round trip through String. (Only works for named colors)
var color = Enum.Parse(typeof(ConsoleColor), color.Name);
EDIT: Here's a link to a question about finding color "closeness".
Josh Einstein
2010-01-01 15:17:13
Is it possible without the Console class?
TTT
2010-01-01 15:22:33
Doesn't appear so. The SetConsoleTextAttribute Win32 API only defines 4 x 1 bit flags for R, G, B, plus an intensity bit. That would only support the 16 colors supported by the ConsoleColor enum.
Josh Einstein
2010-01-01 15:35:36
But you said that the Windows Console support any RGB colors...
TTT
2010-01-01 15:42:40
It does, on Vista and up. You have to P/Invoke SetConsoleScreenBufferInfoEx(), http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/f8fb4005-475d-4edc-99b3-b74519ce5a4e
Hans Passant
2010-01-01 17:46:57