Home > Backend Development > C++ > How Can I Display Custom Colors (Like Orange) in My C# Console Application?

How Can I Display Custom Colors (Like Orange) in My C# Console Application?

Mary-Kate Olsen
Release: 2025-01-02 17:25:40
Original
633 people have browsed it

How Can I Display Custom Colors (Like Orange) in My C# Console Application?

Colorful Text in Console Applications

The built-in ConsoleColor enum provides a limited selection of text colors for C# console applications. However, there may be times when you desire a specific color, such as orange, that's not included.

Limitations of ConsoleColor Enum

The ConsoleColor enum lists the supported text colors, which are:

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

As you can see, orange is not present in this set of colors.

Custom Text Color via P/Invoke

To achieve custom text colors, we can delve into the realms of Platform Invocation (P/Invoke). By utilizing the SetConsoleScreenBufferInfoEx() function from the kernel32.dll library, we can directly manipulate the console's color settings.

First, define the necessary data structures:

[StructLayout(LayoutKind.Sequential)]
internal struct COORD
{
    public short X;
    public short Y;
}

[StructLayout(LayoutKind.Sequential)]
internal struct SMALL_RECT
{
    public short Left;
    public short Top;
    public short Right;
    public short Bottom;
}

[StructLayout(LayoutKind.Sequential)]
internal struct COLORREF
{
    public uint ColorDWORD;
    
    public COLORREF(Color color)
    {
        ColorDWORD = (uint) color.R + (((uint) color.G) << 8) + (((uint) color.B) << 16);
    }
}

[StructLayout(LayoutKind.Sequential)]
internal struct CONSOLE_SCREEN_BUFFER_INFO_EX
{
    public int cbSize;
    public COORD dwSize;
    public COORD dwCursorPosition;
    public ushort wAttributes;
    public SMALL_RECT srWindow;
    public COORD dwMaximumWindowSize;
    public ushort wPopupAttributes;
    public bool bFullscreenSupported;
    ...
}
Copy after login

Then, import the required functions from kernel32.dll:

[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);
Copy after login

Setting Custom Colors

With these tools, we can now define methods to set specific console colors, including orange:

public static int SetColor(ConsoleColor consoleColor, Color targetColor)
{
    // Fetch console details
    CONSOLE_SCREEN_BUFFER_INFO_EX csbe = new CONSOLE_SCREEN_BUFFER_INFO_EX();
    csbe.cbSize = (int)Marshal.SizeOf(csbe);
    IntPtr hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    bool brc = GetConsoleScreenBufferInfoEx(hConsoleOutput, ref csbe);
    if (!brc)
        return Marshal.GetLastWin32Error();

    // Set the specified color component
    switch (consoleColor)
    {
        case ConsoleColor.Black:
            csbe.black = new COLORREF(targetColor);
            break;
        ...
        // Other colors defined similarly
    }
    
    // Apply the Color
    brc = SetConsoleScreenBufferInfoEx(hConsoleOutput, ref csbe);
    if (!brc)
        return Marshal.GetLastWin32Error();
    
    return 0;
}

public static int SetScreenColors(Color foregroundColor, Color backgroundColor)
{
    int irc = SetColor(ConsoleColor.Gray, foregroundColor);
    if (irc != 0) return irc;
    irc = SetColor(ConsoleColor.Black, backgroundColor);
    return irc;
}
Copy after login

Now, let's see an example of SetScreenColors in action:

static void Main(string[] args)
{
    Color screenTextColor = Color.Orange;
    Color screenBackgroundColor = Color.Black;
    SetScreenColors(screenTextColor, screenBackgroundColor);
    
    Console.WriteLine("Hello World!");
    Console.ReadKey();
}
Copy after login

By using the above method, you can set your console's foreground and background colors to any desired RGB values, including orange. Enjoy customizing your console output!

The above is the detailed content of How Can I Display Custom Colors (Like Orange) in My C# Console Application?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template