Colors in c sharp

Custom text color in C# console application?

I just finished my C# console application code for a project and would like to add some color to my font. I would love to be able to use a custom color — orange. Is there any way to do this? This is the code I have been using to change colors in the past, but it doesn’t offer orange:

Console.ForegroundColor = ConsoleColor.Magenta(and so on); 

edited my answer below to include this link. support.microsoft.com/kb/319883 shows blue and red making purple.. just use red and yellow to make orange.

my previous answer was deficient as it didn’t allow you to overwrite the 16 predefined colors, I found the true answer over at the pinvoke.net and updated my answer below with the wall of code. pinvoke.net/default.aspx/kernel32.SetConsoleScreenBufferInfoEx

7 Answers 7

I believe are the only supported colors in console. No hex allowed.

Black DarkBlue DarkGreen DarkCyan DarkRed DarkMagenta DarkYellow Gray DarkGray Blue Green Cyan Red Magenta Yellow White 

Get the working project files off my public Repo

But on further investigation you can do a lot of work to combine red and yellow to get orange. Follow the example here. Not going to re-post wall of code. http://support.microsoft.com/kb/319883 That Doesn’t give you access to more colors but does lead in the correct direction. You will need to do some PINVOKE work but I was easily able to get orange, or any other RGB color into console. http://pinvoke.net/default.aspx/kernel32.SetConsoleScreenBufferInfoEx

// Copyright Alex Shvedov // Modified by MercuryP with color specifications // Use this code in any way you want using System; using System.Diagnostics; // for Debug using System.Drawing; // for Color (add reference to System.Drawing.assembly) using System.Runtime.InteropServices; // for StructLayout class SetScreenColorsApp < [StructLayout(LayoutKind.Sequential)] internal struct COORD < internal short X; internal short Y; >[StructLayout(LayoutKind.Sequential)] internal struct SMALL_RECT < internal short Left; internal short Top; internal short Right; internal short Bottom; >[StructLayout(LayoutKind.Sequential)] internal struct COLORREF < internal uint ColorDWORD; internal COLORREF(Color color) < ColorDWORD = (uint) color.R + (((uint) color.G) internal COLORREF(uint r, uint g, uint b) < ColorDWORD = r + (g internal Color GetColor() < return Color.FromArgb((int) (0x000000FFU & ColorDWORD), (int) (0x0000FF00U & ColorDWORD) >> 8, (int) (0x00FF0000U & ColorDWORD) >> 16); > internal void SetColor(Color color) < ColorDWORD = (uint) color.R + (((uint) color.G) > [StructLayout(LayoutKind.Sequential)] internal struct CONSOLE_SCREEN_BUFFER_INFO_EX < internal int cbSize; internal COORD dwSize; internal COORD dwCursorPosition; internal ushort wAttributes; internal SMALL_RECT srWindow; internal COORD dwMaximumWindowSize; internal ushort wPopupAttributes; internal bool bFullscreenSupported; internal COLORREF black; internal COLORREF darkBlue; internal COLORREF darkGreen; internal COLORREF darkCyan; internal COLORREF darkRed; internal COLORREF darkMagenta; internal COLORREF darkYellow; internal COLORREF gray; internal COLORREF darkGray; internal COLORREF blue; internal COLORREF green; internal COLORREF cyan; internal COLORREF red; internal COLORREF magenta; internal COLORREF yellow; internal COLORREF white; >const int STD_OUTPUT_HANDLE = -11; // per WinBase.h internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // per WinBase.h [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GetConsoleScreenBufferInfoEx(IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFO_EX csbe); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetConsoleScreenBufferInfoEx(IntPtr hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFO_EX csbe); // Set a specific console color to an RGB color // The default console colors used are gray (foreground) and black (background) public static int SetColor(ConsoleColor consoleColor, Color targetColor) < return SetColor(consoleColor, targetColor.R, targetColor.G, targetColor.B); >public static int SetColor(ConsoleColor color, uint r, uint g, uint b) < CONSOLE_SCREEN_BUFFER_INFO_EX csbe = new CONSOLE_SCREEN_BUFFER_INFO_EX(); csbe.cbSize = (int)Marshal.SizeOf(csbe); // 96 = 0x60 IntPtr hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE); // 7 if (hConsoleOutput == INVALID_HANDLE_VALUE) < return Marshal.GetLastWin32Error(); >bool brc = GetConsoleScreenBufferInfoEx(hConsoleOutput, ref csbe); if (!brc) < return Marshal.GetLastWin32Error(); >switch (color) < case ConsoleColor.Black: csbe.black = new COLORREF(r, g, b); break; case ConsoleColor.DarkBlue: csbe.darkBlue = new COLORREF(r, g, b); break; case ConsoleColor.DarkGreen: csbe.darkGreen = new COLORREF(r, g, b); break; case ConsoleColor.DarkCyan: csbe.darkCyan = new COLORREF(r, g, b); break; case ConsoleColor.DarkRed: csbe.darkRed = new COLORREF(r, g, b); break; case ConsoleColor.DarkMagenta: csbe.darkMagenta = new COLORREF(r, g, b); break; case ConsoleColor.DarkYellow: csbe.darkYellow = new COLORREF(r, g, b); break; case ConsoleColor.Gray: csbe.gray = new COLORREF(r, g, b); break; case ConsoleColor.DarkGray: csbe.darkGray = new COLORREF(r, g, b); break; case ConsoleColor.Blue: csbe.blue = new COLORREF(r, g, b); break; case ConsoleColor.Green: csbe.green = new COLORREF(r, g, b); break; case ConsoleColor.Cyan: csbe.cyan = new COLORREF(r, g, b); break; case ConsoleColor.Red: csbe.red = new COLORREF(r, g, b); break; case ConsoleColor.Magenta: csbe.magenta = new COLORREF(r, g, b); break; case ConsoleColor.Yellow: csbe.yellow = new COLORREF(r, g, b); break; case ConsoleColor.White: csbe.white = new COLORREF(r, g, b); break; >++csbe.srWindow.Bottom; ++csbe.srWindow.Right; brc = SetConsoleScreenBufferInfoEx(hConsoleOutput, ref csbe); if (!brc) < return Marshal.GetLastWin32Error(); >return 0; > public static int SetScreenColors(Color foregroundColor, Color backgroundColor) < int irc; irc = SetColor(ConsoleColor.Gray, foregroundColor); if (irc != 0) return irc; irc = SetColor(ConsoleColor.Black, backgroundColor); if (irc != 0) return irc; return 0; >> 

And then if you want to use Orange or any other color you can do a simple call to SetScreenColor

static void Main(string[] args) < Color screenTextColor = Color.Orange; Color screenBackgroundColor = Color.Black; int irc = SetScreenColorsApp.SetScreenColors(screenTextColor, screenBackgroundColor); Debug.Assert(irc == 0, "SetScreenColors failed, Win32Error code = " + irc + " = 0x" + irc.ToString("x")); Debug.WriteLine("LargestWindowHeight=" + Console.LargestWindowHeight + " LargestWindowWidth=" + Console.LargestWindowWidth); Debug.WriteLine("BufferHeight=" + Console.BufferHeight + " WindowHeight=" + Console.WindowHeight + " BufferWidth=" + Console.BufferWidth + " WindowWidth=" + Console.WindowWidth); //// these are relative to the buffer, not the screen: //Debug.WriteLine("WindowTop=" + Console.WindowTop + " WindowLeft=" + Console.WindowLeft); Debug.WriteLine("ForegroundColor=" + Console.ForegroundColor + " BackgroundColor=" + Console.BackgroundColor); Console.WriteLine("Some text in a console window"); Console.BackgroundColor = ConsoleColor.Cyan; Console.ForegroundColor = ConsoleColor.Yellow; Debug.WriteLine("ForegroundColor=" + Console.ForegroundColor + " BackgroundColor=" + Console.BackgroundColor); Console.Write("Press ENTER to exit. "); Console.ReadLine(); // Note: If you use SetScreenColors, the RGB values of gray and black are changed permanently for the console window. // Using i.e. Console.ForegroundColor = ConsoleColor.Gray afterwards will switch the color to whatever you changed gray to // It's best to use SetColor for the purpose of choosing the 16 colors you want the console to be able to display, then use // Console.BackgroundColor and Console.ForegrondColor to choose among them. >

Источник

Читайте также:  Float диапазон значений java

Defining colors as constants in C#

As far as I am aware, readonly is essentially a constant for my purposes. If I attempt to define these as constants, the compiler indicates that it must be a compile-time constant, which Color is not. Am I good leaving these as-is, or is there some way to define these constants that I should be aware of? (The purpose is simply to have a single location in which to change all of the colors for logging purposes.)

6 Answers 6

Only literals can be defined as const . The difference is, that const values are hard-bakened into the assemblies that uses it. Should their definition change, then the call sites doesn’t notice unless they get recompiled.

In contrast, readonly declares a variable in a way that it cannot be reassigned after outside the constructor (or static constructor in case of a static readonly variable).

So, you have no other way then to use readonly here, since Color is a struct, and no primitive data type or literal.

This is very important, and I would go as far to say that it supports the idea that readonly static is the preferred way to const .

A const field is a compile time constant — you actually need code to run to determine the value of Color.Orange though, internally probably defined as

public static readonly Color Orange = new Color(. ); 

Since this cannot be computed at compile time, your only option is readonly which is set at runtime.

Aside from the technical aspects that others have mentioned (that const values are replaced at compile-time in the places they are used, and are required to be literals rather than static readonly values which are assigned and referenced at runtime) there is a semantic issue to consider.

The reason const values are replaced at compile-time is that const really does mean «constant» — as in a value that will never, ever change such as pi or e. That’s why it’s safe to replace them at compile-time, because the name represents a forever unchanging value.

The purpose is simply to have a single location in which to change all of the colors for logging purposes.

. indicates that these are not semantically constant, and thus should not be defined as const even if it were possible to do so.

Источник

C# Color Object

The C# Color Object is a very convenient way of storing colors in your C# projects. Once you have a Color object you can easily get the RGB and HSB values out of it.

Understanding the Color object is important if you are learning to do any C# work that involves colors.

Creating Color Objects

If you have an HTML color code and you want to make a Color object then you may want to read about how to Create C# Color Objects from HTML Color Codes. The easiest way to create a Color object is from a known color.

// you can specify known color names var lightGray = Color.LightGray; 

If you happen to have the color that you need in a string you can specify it that way as well.

// the color can even be in a string var lightGray = Color.FromName("lightgray"); 

If you need to test if the color returned is valid you can look at the alpha channel. It will be 0 for a bad color name.

var lightGray = Color.FromName("not-a-color"); if (lightGray.A == 0)

If you want to translate a typed in color string to a proper known color value you can do that too.

var lightGray = Color.FromName("lightgray"); if (lightGray.IsKnownColor) < var colorName = lightGray.ToKnownColor().ToString(); // colorName is a string with the text "LightGray" in it >

C# Color Object

Once you have a Color object you can get the individual Red, Green, and Blue components as well as the Alpha (transperancy).

// if you want to retrieve the RGB values of a color it's very simple var red = lightGray.R; var green = lightGray.G; var blue = lightGray.B; var alpha = lightGray.A; 

If you need to be in the HSB (Hue, Saturation, Brightness) gamut it’s just as easy.

// if you want the HSB values you can easily get those var hue = lightGray.GetHue(); var saturation = lightGray.GetSaturation(); var brightness = lightGray.GetBrightness(); 

C# Image Processing

Be sure to check out our other C# Image Processing Guides located here.

Источник

Оцените статью