0

does anyone of you lot know a way to use colors in a program compiled in Dev C++, except for the

system("color a");

function?

and I'd also be glad to know another way to clear the screen, then the:

system("cls");

function

4
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by Tom Gunn
0

SetConsoleTextAttribute can change the foreground and background:

#include <iostream>
#include <windows.h>

using namespace std;

HANDLE SetColor(
                HANDLE console, 
                int fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
                int bg = 0)
{
    if (console == NULL)
        console = GetStdHandle(STD_OUTPUT_HANDLE);

    SetConsoleTextAttribute(console, fg | bg);

    return console;
}

int main()
{
    HANDLE console = SetColor(NULL, FOREGROUND_RED, BACKGROUND_GREEN);

    cout << "Hello world!\n";
    SetColor(console);
    cout << "All done.\n";
}

and I'd also be glad to know another way to clear the screen

Here is a windows way:

void clear_screen()
{
    DWORD n, size;
    COORD coord = {0};
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);

    GetConsoleScreenBufferInfo(h, &csbi);
    size = csbi.dwSize.X * csbi.dwSize.Y;
    FillConsoleOutputCharacter(h, TEXT(' '), size, coord, &n);
    GetConsoleScreenBufferInfo(h, &csbi);
    FillConsoleOutputAttribute(h, csbi.wAttributes, size, coord, &n);
    SetConsoleCursorPosition(h, coord);
}
0

Thank you, this helped a lot!

just one question, could you use any othe colors then blue, green, red?

0

just one question, could you use any othe colors then blue, green, red?

You can combine red green and blue just like in art class. :) Put them together with a binary or:

#include <iostream>
#include <windows.h>

using namespace std;

HANDLE SetColor(
                HANDLE console, 
                int fg = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,
                int bg = 0)
{
    if (console == NULL)
        console = GetStdHandle(STD_OUTPUT_HANDLE);

    SetConsoleTextAttribute(console, fg | bg);

    return console;
}

int main()
{
    HANDLE console = SetColor(NULL, FOREGROUND_RED, BACKGROUND_GREEN);

    cout << "Hello world!\n";
    SetColor(console, FOREGROUND_BLUE | FOREGROUND_GREEN);
    cout << "Teal.\n";
    SetColor(console, FOREGROUND_RED | FOREGROUND_BLUE);
    cout << "Purple.\n";
    SetColor(console);
}

You should read the link to SetConsoleTextAttribute. The character attributes page shows how to do all of this.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.