What is the best way to convert a System.Drawing.Color
to a similar System.ConsoleColor
?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
On Vista and later see the SetConsoleScreenBufferInfoEx API function.
For an example of usage refer to my answer to another very similar StackOverflow question. (Thanks Hans Passant for original answer).
The distinct default "white-on-blue" color of PowerShell.exe before version 6 (and any ConsoleWindowClass window) is actually DarkYellow on DarkMagenta if you check
$Host.UI.RawUI
. This is because theConsoleColor
enum values are just indices into the console color table, which is configurable (see this answer about DarkYellow).Here are the hex RGB values for the default console color table:
The ConsoleColors enumeration seems to use the EGA style palette ordering, which is:
You can roughly map a 24-bit colour (or 32-bit colour, by ignoring the alpha channel) to what is essentially 3-bit colour with a brightness component. In this case, the 'brightness' bit is set if any of the System.Drawing.Color's red, green or blue bytes are greater than 128, and the red, green, blue bits are set if the equivalent source bytes are higher than 64.
You can use reflection.
Usage:
Easy one...
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:
Or if performance is not that important, you can round trip through String. (Only works for named colors)
EDIT: Here's a link to a question about finding color "closeness".