change console color c# code example

Example 1: c# console background color

Console.BackgroundColor = ConsoleColor.Green;

Example 2: c# hex to console color

public static ConsoleColor FromHex(string hex)
    {
        int argb = Int32.Parse(hex.Replace("#", ""), NumberStyles.HexNumber);
        Color c = Color.FromArgb(argb);
        
        int index = (c.R > 128 | c.G > 128 | c.B > 128) ? 8 : 0; // Bright bit
        index |= (c.R > 64) ? 4 : 0; // Red bit
        index |= (c.G > 64) ? 2 : 0; // Green bit
        index |= (c.B > 64) ? 1 : 0; // Blue bit
        
        return (System.ConsoleColor)index;
    }

Example 3: c# change colour of console

Console.BackgroundColor = ConsoleColor.Green;
            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.Clear();
            //green on green
            Console.WriteLine("yo");
            Console.ReadLine();

Example 4: c# color to console color

public static ConsoleColor FromColor(Color c)
        {
            int index = (c.R > 128 | c.G > 128 | c.B > 128) ? 8 : 0; // Bright bit
            index |= (c.R > 64) ? 4 : 0; // Red bit
            index |= (c.G > 64) ? 2 : 0; // Green bit
            index |= (c.B > 64) ? 1 : 0; // Blue bit

            return (System.ConsoleColor)index;
        }

Tags: