在Windows控制台编程中,SetConsoleTextAttribute
函数用于设置控制台文本的颜色和背景色。该函数的第二个参数是一个组合值,由前景色和背景色两部分组成。每个颜色部分占用4位,因此总共有8位(一个字节)。
| 颜色 | 数值 | |------|------| | 黑色 | 0 | | 蓝色 | 1 | | 绿色 | 2 | | 青色 | 3 | | 红色 | 4 | | 紫色 | 5 | | 黄色 | 6 | | 白色 | 7 | | 灰色 | 8 | | 淡蓝色 | 9 | | 淡绿色 | 10 | | 淡青色 | 11 | | 淡红色 | 12 | | 淡紫色 | 13 | | 淡黄色 | 14 | | 亮白色 | 15 |
给定的值192
可以分解为前景色和背景色。具体步骤如下:
以下是一个C语言示例代码,展示如何分解颜色值192
:
#include <windows.h>
#include <stdio.h>
void PrintColorComponents(int color) {
int backgroundColor = (color >> 4) & 0xF;
int foregroundColor = color & 0xF;
printf("Color 192 decomposed as:\n");
printf("Background Color: %d\n", backgroundColor);
printf("Foreground Color: %d\n", foregroundColor);
}
int main() {
HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
if (hStdout == INVALID_HANDLE_VALUE) {
printf("Failed to get standard output handle.\n");
return 1;
}
PrintColorComponents(192);
// Example usage of SetConsoleTextAttribute
SetConsoleTextAttribute(hStdout, 192);
printf("This text has a decomposed color of Background: %d, Foreground: %d\n", (192 >> 4) & 0xF, 192 & 0xF);
SetConsoleTextAttribute(hStdout, 7); // Reset to default
return 0;
}
运行上述代码后,输出将会是:
Color 192 decomposed as:
Background Color: 12
Foreground Color: 0
This text has a decomposed color of Background: 12, Foreground: 0
192
右移4位后得到12
(即淡红色)。192
的低4位是0
(即黑色)。这种分解方法常用于需要动态设置控制台文本颜色和背景色的应用程序,例如日志记录工具、交互式命令行工具等。
通过这种方式,开发者可以灵活地组合不同的颜色,以满足不同的显示需求。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云