【问题标题】:Console coloring in C not working correctlyC 中的控制台着色无法正常工作
【发布时间】:2016-10-26 06:11:31
【问题描述】:

我正在尝试用 C 编写一个简单的应用程序,我对 C 的概念还很陌生,所以如果这很简单,我深表歉意。我正在运行 Windows 7,并且有一些类似的东西:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>

#define Green   "\33[0:32m"
#define Yellow  "\33[0:33m"
#define Reset   "\33[0m"
#define Log_info(X) printf("[Info] %s %s %s\n", Green,X,Reset)
#define Log_warn(X) printf("[Warning] %s %s %s\n",Yellow,X,Reset)
#define Seperator() printf("----------------------------------------------------\n")

void info(const char *message)
{  
    Log_info(message);
    Seperator();
}

void warn(const char *message)
{
    Log_warn(message);
    Seperator();
}

int main(int argc, char *argv[])
{
    warn("test the warning output for the console");
    info("test the information output for the console");
}

但是,当我尝试运行信息处理时,我得到以下信息:

[Warning] ←[0:33m test the warning output for the console ←[0m
----------------------------------------------------
[Info] ←[0:32m test the information output for the console ←[0m
----------------------------------------------------

我做错了什么以至于不是颜色协调输出,而是使用箭头?如何颜色协调信息,黄色表示警告,绿色表示信息?

我想到了使用 \33[0:32m 主要来自 Javascript (\033[32m #&lt;=Green) 和 Ruby (\e[32m #&lt;=Green)。

【问题讨论】:

    标签: c colors windows-7 console


    【解决方案1】:

    您没有使用正确的颜色代码。而且这些颜色代码仅适用于具有兼容终端的 Unix 系统。

    由于您需要特定于 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

    【讨论】:

    • 这就解释了!嘿,谢谢,顺便说一句,我看过你的 github,我喜欢 Khronos
    • @JohnDoeYo 谢谢!随意给它加星标,并在某个时候尝试一下!我现在正在努力让它在 Windows 上编译。
    • 你认为有办法将它添加到头文件中,就像你原来的答案一样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2018-10-01
    • 2015-12-29
    相关资源
    最近更新 更多