windows终端应用程序中的C颜色文本 [英] C color text in terminal applications in windows

查看:17
本文介绍了windows终端应用程序中的C颜色文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道textcolor();"是针对 C++ 的,我已经看到了针对 unix 的方法......但是窗户也有办法吗?

I know "textcolor();" is for C++ and i've seen methods for unix... but is there way for windows also?

#include <stdio.h>
int main()
{
    printf("
test - C programming text color!");
    printf("
--------------------------------");
    printf("

		-BREAK-

");
    textcolor(15);
    printf("WHITE
");
    textcolor(0);
    printf("BLACK
");
    textcolor(4);
    printf("RED
");
    textcolor(1);
    printf("BLUE
");
    textcolor(2);
    printf("GREEN
");
    textcolor(5);
    printf("MAGENTA
");
    textcolor(14);
    printf("YELLOW
");
    textcolor(3);
    printf("CYAN
");
    textcolor(7);
    printf("LIGHT GRAY
");
}

我在网上找不到任何东西...让我们希望堆栈溢出的好人可以提供帮助:D

I can't find any anything on the net... let's hope the good people from stack overflow can help :D

请使用 C,而不是 C++

C please, not C++

推荐答案

由于您需要 C 和 Windows 特定的解决方案,我建议使用 Win32 API 中的 SetConsoleTextAttribute() 函数.您需要获取控制台的句柄,然后将其与适当的属性一起传递.

Since you want a C and Windows specific solution, I'd recommend using the SetConsoleTextAttribute() function in the Win32 API. You'll need to grab a handle to the console, and then pass it with the appropriate attributes.

举个简单的例子:

/* 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;
}

有关可用属性的详细信息,请查看 这里.

For more info on the available attributes, look here.

希望这有帮助!:)

这篇关于windows终端应用程序中的C颜色文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆