Windows 终端应用程序中的 C 颜色文本

标签 c windows cmd command-prompt textcolor

我知道“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/

相关文章:

c++ - 在终止 c++ 之前调用函数

c++ - MFC 应用程序热键和加速器哪个更好?

python - 如何从命令行在 python 2.7 和 python 3 之间切换?

c - 使用 Posix 正则表达式搜索多个 URL 模式

c - 将十六进制字符串转换为字节数组的预处理器宏

c++ - 是否有适用于 mac 的 FindWindow() 替代品?

windows - 如何使用批处理文件删除父文件夹中的特定子文件夹?

linux - 通过单个命令行操作确定操作系统

我们可以声明数组的大小为零吗?

objective-c - ObjC 宏 ifdef 和定义