在Windows终端应用C色系彩色文本 [英] C color text in terminal applications in windows

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

问题描述

我知道文本颜色();是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("\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");
}

我无法在网络上找到的任何东西......
让我们希望从堆栈溢出的好心人能帮助: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具体的解决办法,我建议使用 SetConsoleTextAttribute()功能在Win32 API。你需要抓住一个句柄到控制台,然后用适当的属​​性传递。

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

有关可用属性的详细信息

,看<一个href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088%28v=vs.85%29.aspx#_win32_character_attributes\">here.

For more info on the available attributes, look here.

希望这有助于! :)

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

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