C Program To Change The Colour Of Console Table
Customizing the console's appearance can significantly improve the readability and user experience of command-line applications. By changing text and background colors, you can highlight critical information, differentiate output types, and add a professional touch to your programs. In this article, you will learn various C programming approaches to change console text and background colors, covering both Windows-specific methods and cross-platform solutions.
Problem Statement
Standard C output, typically achieved with printf, is monochrome by default. This limitation can make it challenging to convey nuanced information or draw a user's attention to specific messages like errors, warnings, or successes. Without color, distinguishing between different types of program output requires careful parsing by the user, which can lead to missed alerts or a less intuitive experience.
Example
Consider a simple program that outputs different messages. When executed, you would see text like this, but with actual colors applied:
This is a regular message.
This is a success message! (displayed in green)
This is an error message! (displayed in red)
This example visually demonstrates how colors can enhance the message's impact and immediacy.
Background & Knowledge Prerequisites
To effectively follow this tutorial, you should have a basic understanding of:
- C Programming Fundamentals: Variables, data types, control structures (if/else, loops), and function calls.
-
printfFunction: How to useprintffor standard output. - Header Files: The concept of including necessary header files (e.g.,
stdio.h,windows.h). - Operating System Basics: An awareness that certain functions might be OS-specific.
No special setup is required beyond a C compiler (like GCC or Clang) and a text editor or IDE.
Use Cases or Case Studies
Changing console colors can be useful in a variety of scenarios:
- Error and Warning Notifications: Displaying error messages in red and warnings in yellow makes them instantly noticeable to the user.
- Status Indicators: Showing success messages in green or informational messages in blue provides clear feedback on program execution.
- Text-Based Games: Enhancing simple console games by coloring characters, items, or environment elements for better visual distinction.
- Log File Analysis: Highlighting specific log entries (e.g., critical errors, specific user actions) when tailing or displaying logs in the console.
- Interactive Command-Line Tools: Improving the user interface of CLI tools by using colors for prompts, menu options, or user input fields.
Solution Approaches
There are primarily two main approaches to changing console colors in C, depending on the target operating system and terminal environment.
Approach 1: Using SetConsoleTextAttribute (Windows Specific)
This approach leverages the Windows API to directly control the console's text and background attributes. It offers robust control over color and intensity on Windows systems.
- Summary: This method uses functions from the
windows.hheader to directly manipulate the console's screen buffer attributes, allowing for precise control over foreground and background colors. - Code Example:
// Windows Console Color Example
#include <stdio.h>
#include <windows.h> // Required for Windows API functions
int main() {
// Step 1: Get a handle to the standard output console
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
// Step 2: Store original console attributes to restore later
CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
WORD originalAttrs = consoleInfo.wAttributes;
// Step 3: Set text color to green (FOREGROUND_GREEN)
SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
printf("This text is green and bright!\\n");
// Step 4: Set text color to red (FOREGROUND_RED) and background to yellow (BACKGROUND_YELLOW)
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | BACKGROUND_YELLOW);
printf("This text is red with a yellow background!\\n");
// Step 5: Set text color to blue with high intensity
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_INTENSITY);
printf("This is a bright blue informational message.\\n");
// Step 6: Restore original console attributes before exiting
SetConsoleTextAttribute(hConsole, originalAttrs);
printf("This text is back to default.\\n");
return 0;
}
- Sample Output:
cmd.exe or PowerShell), you will observe:
- The first line "This text is green and bright!" will appear in bright green text.
- The second line "This text is red with a yellow background!" will appear in red text on a yellow background.
- The third line "This is a bright blue informational message." will appear in bright blue text.
- The final line "This text is back to default." will revert to the console's default text color.
- Stepwise Explanation:
- Include
windows.hto access Windows API functions. - Use
GetStdHandle(STD_OUTPUT_HANDLE)to obtain a handle to the console's standard output buffer. This handle is necessary for console manipulation functions. - Optionally, use
GetConsoleScreenBufferInfoto retrieve and store the console's current attributes. This allows you to restore the default colors later. - Call
SetConsoleTextAttributewith the console handle and aWORDvalue representing the desired attributes. These attributes are a bitmask, combiningFOREGROUND_*for text color andBACKGROUND_*for background color.FOREGROUND_INTENSITYcan be added for a brighter foreground color. - Print your text using
printf. The text will inherit the currently set attributes. - Always restore the original attributes using
SetConsoleTextAttributewith theoriginalAttrsvalue to ensure the console returns to its default state for subsequent output or other programs.
Approach 2: Using ANSI Escape Codes (Cross-platform for compatible terminals)
ANSI escape codes are special character sequences that compatible terminals interpret as commands to change text formatting, including colors. This method is widely supported on Unix-like systems (Linux, macOS) and modern Windows terminals (like Windows Terminal, VS Code terminal, and recent versions of cmd.exe and PowerShell).
- Summary: This approach involves embedding specific non-printable character sequences (escape codes) directly into your
printfstrings. These codes instruct the terminal to change text or background colors until a reset code is encountered. - Code Example:
// ANSI Escape Codes Console Color Example
#include <stdio.h>
// ANSI foreground color codes
#define ANSI_COLOR_RED "\\x1b[31m"
#define ANSI_COLOR_GREEN "\\x1b[32m"
#define ANSI_COLOR_YELLOW "\\x1b[33m"
#define ANSI_COLOR_BLUE "\\x1b[34m"
#define ANSI_COLOR_MAGENTA "\\x1b[35m"
#define ANSI_COLOR_CYAN "\\x1b[36m"
#define ANSI_COLOR_RESET "\\x1b[0m" // Reset to default attributes
// ANSI background color codes
#define ANSI_BG_RED "\\x1b[41m"
#define ANSI_BG_GREEN "\\x1b[42m"
#define ANSI_BG_YELLOW "\\x1b[43m"
#define ANSI_BG_BLUE "\\x1b[44m"
#define ANSI_BG_MAGENTA "\\x1b[45m"
#define ANSI_BG_CYAN "\\x1b[46m"
int main() {
// Step 1: Print text in green
printf(ANSI_COLOR_GREEN "This text is green.\\n" ANSI_COLOR_RESET);
// Step 2: Print text in red with a yellow background
printf(ANSI_COLOR_RED ANSI_BG_YELLOW "This text is red with a yellow background.\\n" ANSI_COLOR_RESET);
// Step 3: Combine colors and styles (e.g., bold blue text)
printf("\\x1b[1;34m" "This is bold blue text.\\n" ANSI_COLOR_RESET); // 1 = bold, 34 = blue foreground
// Step 4: A warning message in yellow
printf(ANSI_COLOR_YELLOW "WARNING: Something might be wrong!\\n" ANSI_COLOR_RESET);
// Step 5: An error message in red
printf(ANSI_COLOR_RED "ERROR: Critical failure detected!\\n" ANSI_COLOR_RESET);
return 0;
}
- Sample Output:
- The first line "This text is green." will appear in green text.
- The second line "This text is red with a yellow background." will appear in red text on a yellow background.
- The third line "This is bold blue text." will appear in bold blue text.
- The fourth line "WARNING: Something might be wrong!" will appear in yellow text.
- The fifth line "ERROR: Critical failure detected!" will appear in red text.
- Stepwise Explanation:
- Define string macros (e.g.,
ANSI_COLOR_RED) that contain the specific ANSI escape sequences. These sequences start with\x1b[(the escape character followed by a left square bracket). - For foreground colors, use codes like
31m(red) up to36m(cyan). For background colors, use41m(red) up to46m(cyan). \x1b[0mis the crucial "reset" code, which reverts all text attributes (color, bold, etc.) to their default state. It's vital to include this after any colored text to avoid coloring subsequent output unintentionally.- Concatenate these ANSI codes directly into your
printfstrings. The terminal interprets the codes, applies the styling, and then prints the text that follows. - ANSI codes can also specify styles like bold (
\x1b[1m), underline (\x1b[4m), and more, often combined with color codes (e.g.,\x1b[1;34mfor bold blue).
Conclusion
Changing console colors in C provides a powerful way to enhance the user interface and readability of command-line applications. The choice between SetConsoleTextAttribute (Windows-specific) and ANSI escape codes (cross-platform for compatible terminals) depends on your target operating system and the intended environment for your application. Both methods offer effective solutions for bringing color to your console programs, making them more engaging and informative for users.
Summary
- Windows-specific coloring: Use
SetConsoleTextAttributefromwindows.hfor precise control over text and background colors on Windows. - Cross-platform coloring: Employ ANSI escape codes (e.g.,
\x1b[31mfor red text) by embedding them directly intoprintfstrings. This works on most Unix-like terminals and modern Windows terminals. - Reset is crucial: Always use the
ANSI_COLOR_RESET(\x1b[0m) code after applying ANSI colors to prevent subsequent output from being colored unexpectedly. - Enhance UX: Colored output improves readability, highlights important information, and makes console applications more user-friendly.