#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2005
    Posts
    8
    Rep Power
    0

    Colors in a console program?


    Is there an easy way to put colors in my console program?

    I make the menu with PRINTF
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,642
    Rep Power
    4247
    Depends on your compiler/environment. For instance, Turbo-C family (and QuickC possibly) had setcolor() and cprintf(). If you want to use Windows AP I calls, you probably want to use WriteConsoleOutputAttribute() for this. See http://msdn.microsoft.com/library/de...tive_cells.asp for an example.

    Another way would be to use the ANSI.SYS driver in your console and output ANSI escape sequences.

    I would go with the WriteConsoleOutputAttribute() method.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    62
    Rep Power
    4

    Console colour programme.


    I'm currently writing a Windows console application, and wrote a short demonstrator of how the colour attributes work, I can't post a link to the pastebin, so the code is below.

    There are some other useful routines in there for anyone interested in making a quick Windows console app.

    As the Windows Console uses two nybbles for the colours, with the upper nybbles being background and the lower being foreground colour, which is kind of like the attributes on a Sinclair ZX Spectrum but without the bright and flash attributes.

    Regards,

    Shaun.
    Code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>
    #include <windows.h>
    #define SETCOLOUR(a,b)  a<<4|b
    
    /**
     * A programme demonstrating the use of colour nybbles for Windows
     * Tested using Code::Blocks and Windows 7 Professional SP1
     *
     * @Author:     Shaun B
     * @Version:	1.0.0.3 - 2012-09-12
     * @Todo:
     * @Changes:    Refactored with varibale names that might make sense
     *              Found an odd bug with the release build, which is now
     *              fixed.
     *
     **/
    
    int main();
    void gotoxy(int, int);
    void hideCursor();
    
    /// Sets variables for:
    ///     Running boolean -
    static bool run = true;
    ///     Reusable variables -
    static unsigned char index[2] = "";
    static unsigned char count = 0;
    static unsigned char xAxis = 0;
    static unsigned char yAxis = 0;
    static unsigned char character [2] = "";
    
    int main()
    {
        // Sets default console size, colours and title:
        system("mode CON: COLS=80 LINES=25");
        system("cls");
        system("title Demonstrating the use of colour nybbles Donkeysoft MMXII");
        system("echo off");
        HANDLE hConsole;
        // Switches off blinking cursor:
        hConsole=   GetStdHandle(STD_OUTPUT_HANDLE);
        hideCursor();
        // Sets cursor position for each scrolly text:
        gotoxy(0, 0);
        printf("For console applications, the colours are defined in a byte, so f0 would"
               "\ngive you white background and black text.\n");
        printf("Enter a byte in hex (00 - ff) to see what happens. Space to exit programme.\n");
        xAxis=  4;
        yAxis=  3;
        printf("C:\\>");
        // Main loop:
        while(run)
        {
            gotoxy(xAxis, yAxis);
            printf("");
            // Scans keyboard into buffer:
            character[count] = _getch();
            if(character[count] == 32)
            {
                run=false;
            }
            else
            if(character[count] >= 48 && character[count] <= 57 && count < 2)
            {
                gotoxy(xAxis, yAxis);
                printf("%c", character[count]);
                index[count] = character[count]-48;
                xAxis++;
                count++;
            }
            else
            if(character[count] >= 97 && character[count] <= 102 && count < 2)
            {
                gotoxy(xAxis, yAxis);
                printf("%c", character[count]);
                index[count] = character[count]-87;
                xAxis++;
                count++;
            }
            else
            if(character[count] >= 65 && character[count] <= 70 && count < 2)
            {
                gotoxy(xAxis, yAxis);
                printf("%c", character[count]);
                index[count] = character[count]-55;
                xAxis++;
                count++;
            }
            else
            if(character[count] == 13 && count == 2)
            {
                gotoxy(xAxis-2, yAxis);
                printf("   ");
                unsigned char kCol = (unsigned char) SETCOLOUR(index[0], index[1]);
                SetConsoleTextAttribute(hConsole, kCol);
                printf("\nNew colour set to %3d!", kCol);
                xAxis = 4;
                count = 0;
                kCol = 0;
                index[2] = '\0';
                character[2] =  '\0';
                gotoxy(0, yAxis);
                printf("C:\\>");
                if(!run)
                {
                    run = true;
                }
            }
            else
            {
                character[count] = '\0';
            }
        }
        system("color f0");
        system("cls");
        printf("Cheers!");
        // Returns when loop is exited:
        return 0;
    }
    
    // Sets co-ordinates within the command line:
    void gotoxy(int x, int y)
    {
        COORD coord;
        coord.X = x;
        coord.Y = y;
        SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
    }
    
    // Turns off blinking cursor:
    void hideCursor()
    {
        CONSOLE_CURSOR_INFO lpCursor;
        lpCursor.bVisible = 0;
        lpCursor.dwSize = 20;
        SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE),&lpCursor);
    }
    
    /** This routine is no longer needed, replaced with the pre-processor symbol at the top.
    unsigned char setColour(unsigned char a, unsigned char b)
    {
        if(i[0]!=a && i[1]!=b)
        {
            // Just in case there's an odd error...
            return -1;
        }
        else
        {
            // Bitwise shift a four bits and then 'or' with b
            return (a<<4)|b;
        }
    }*/
    Last edited by Shaun_B; September 12th, 2012 at 07:19 AM. Reason: Found a better way to do the bitwise stuff - found a bug with the release build (won't make much difference, but...)
  6. #4
  7. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,114
    Rep Power
    1803
    You need to use the Win32 Console API in particular
    SetConsoleTextAttribute().
  8. #5
  9. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,905
    Rep Power
    481
    Or use an ANSI terminal with escape sequences

    Or use ncurses

    but whatever, I guess you mentioned windows.
    [code]Code tags[/code] are essential for python code and Makefiles!
  10. #6
  11. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,642
    Rep Power
    4247
    Guys, the OP's post and my reply date from 7 years ago :)

    Comments on this post

    • DaWei_M agrees : Amen
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  12. #7
  13. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,114
    Rep Power
    1803
    Originally Posted by b49P23TIvg
    That no longer works in Windows. MS-DOS provided a 16 bit ansi.sys but that was a very long time ago. If you know of a way to make it work I'd be interested! ;)
  14. #8
  15. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,114
    Rep Power
    1803
    Originally Posted by Scorpions4ever
    Guys, the OP's post and my reply date from 7 years ago :)
    Posting a "disagree" against the necromancer might have made that more obvious!

IMN logo majestic logo threadwatch logo seochat tools logo