如何在C ++中用Windows上的代码块输出彩色文本? [英] How to output colored text in C++ with codeblocks on Windows?

查看:112
本文介绍了如何在C ++中用Windows上的代码块输出彩色文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

从控制台C ++应用程序将stdout输出到Windows cmd.exe

我在Windows XP上使用代码块,我需要一种方法来输出彩色文本,也可能在控制台应用程序中更改背景颜色。

我尝试了 conio.h 函数,但是它们似乎与代码块不兼容。

I am using codeblocks on Windows XP and I need a way to output colored text, and maybe change the color of the background as well in a console application.
I tried the conio.h functions but they don't seem to be compatible with code blocks.

推荐答案

看起来您希望使用一些Windows API功能来完成此操作。

It looks like you'll want to use some Windows API features to accomplish this.
If you were using Cygwin for windows, it'd be a bit easier.

这里是示例由daniweb提供:

Here's an example courtesy of daniweb:

// color your text in Windows console mode
// colors are 0=black 1=blue 2=green and so on to 15=white
// colorattribute = foreground + background * 16
// to get red text on yellow use 4 + 14*16 = 228
// light red on yellow would be 12 + 14*16 = 236
// a Dev-C++ tested console application by vegaseat 07nov2004

#include <iostream>
#include <windows.h> // WinApi header

using namespace std; // std::cout, std::cin

int main()
{
    HANDLE hConsole;
    int k;

    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);

    // you can loop k higher to see more color choices
    for(k = 1; k < 255; k++)
    {
        // pick the colorattribute k you want
        SetConsoleTextAttribute(hConsole, k);
        cout << k << " I want to be nice today!" << endl;
    }

    cin.get(); // wait
    return 0;
}

这篇关于如何在C ++中用Windows上的代码块输出彩色文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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