我知道“textcolor();”适用于 C++,我见过适用于 unix 的方法... 但是 Windows 也有办法吗?
#include <stdio.h>
int main()
{
printf("\ntest - C programming text color!");
printf("\n--------------------------------");
printf("\n\n\t\t-BREAK-\n\n");
textcolor(15);
printf("WHITE\n");
textcolor(0);
printf("BLACK\n");
textcolor(4);
printf("RED\n");
textcolor(1);
printf("BLUE\n");
textcolor(2);
printf("GREEN\n");
textcolor(5);
printf("MAGENTA\n");
textcolor(14);
printf("YELLOW\n");
textcolor(3);
printf("CYAN\n");
textcolor(7);
printf("LIGHT GRAY\n");
}
我在网上找不到任何东西... 希望 stack overflow 的好心人能帮上忙 :D
请使用 C,而不是 C++
最佳答案
由于您需要 C 和 Windows 特定的解决方案,我建议使用 Win32 API 中的 SetConsoleTextAttribute()
函数。您需要获取控制台的句柄,然后将其与适当的属性一起传递。
举个简单的例子:
/* Change console text color, then restore it back to normal. */
#include <stdio.h>
#include <windows.h>
int main() {
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
WORD saved_attributes;
/* Save current attributes */
GetConsoleScreenBufferInfo(hConsole, &consoleInfo);
saved_attributes = consoleInfo.wAttributes;
SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE);
printf("This is some nice COLORFUL text, isn't it?");
/* Restore original attributes */
SetConsoleTextAttribute(hConsole, saved_attributes);
printf("Back to normal");
return 0;
}
有关可用属性的更多信息,请查看 here .
希望对您有所帮助! :)
关于Windows 终端应用程序中的 C 颜色文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9203362/