Win32 Console Application Tools



Click here for larger image

Environment: VC6, SP5, WinXP; should also work on Win9x

I decided to make these routines public after looking for a long time to find them.

  • void clrscr();
  • void gotoxy(x,y);
  • void setrgb(color);

The code to accomplish this follows.

// console.cpp
//
#include "console.h"

using namespace std;

//
// Clears the screen
//
void clrscr()
{
  COORD coordScreen = { 0, 0 }; 
  DWORD cCharsWritten; 
  CONSOLE_SCREEN_BUFFER_INFO csbi; 
  DWORD dwConSize; 
  HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); 
  
  GetConsoleScreenBufferInfo(hConsole, &csbi); 
  dwConSize = csbi.dwSize.X * csbi.dwSize.Y; 
  FillConsoleOutputCharacter(hConsole, TEXT(' '),
                             dwConSize, 
                             coordScreen,
                             &cCharsWritten); 
  GetConsoleScreenBufferInfo(hConsole, &csbi); 
  FillConsoleOutputAttribute(hConsole,
                             csbi.wAttributes,
                             dwConSize,
                             coordScreen,
                             &cCharsWritten); 
  SetConsoleCursorPosition(hConsole, coordScreen); 
}

//
// Moves the cursor to x, y in console window
// ie x=left\right y=top\bottom
//
void gotoxy(int x, int y)
{
  COORD point;
  point.X = x; point.Y = y;
  SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),
                           point);
}

//
// Set text and background colors
//
void setrgb(int color)
{
  switch (color)
  {
  case 0:    // White on Black
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                        FOREGROUND_INTENSITY | FOREGROUND_RED |
                        FOREGROUND_GREEN | FOREGROUND_BLUE);
    break;
  case 1:    // Red on Black
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                         FOREGROUND_INTENSITY | FOREGROUND_RED);
    break;
  case 2:    // Green on Black
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                      FOREGROUND_INTENSITY | FOREGROUND_GREEN);
    break;
  case 3:    // Yellow on Black
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                      FOREGROUND_INTENSITY | FOREGROUND_RED |
                      FOREGROUND_GREEN);
    break;
  case 4:    // Blue on Black
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                      FOREGROUND_INTENSITY | FOREGROUND_BLUE);
    break;
  case 5:    // Magenta on Black
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                     FOREGROUND_INTENSITY | FOREGROUND_RED |
                     FOREGROUND_BLUE);
    break;
  case 6:    // Cyan on Black
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                    FOREGROUND_INTENSITY | FOREGROUND_GREEN |
                    FOREGROUND_BLUE);
    break;
  case 7:    // Black on Gray
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                  BACKGROUND_INTENSITY | BACKGROUND_INTENSITY);
    break;
  case 8:    // Black on White
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                  BACKGROUND_INTENSITY | FOREGROUND_INTENSITY |
                  BACKGROUND_RED | BACKGROUND_GREEN |
                  BACKGROUND_BLUE);
    break;
  case 9:    // Red on White
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                  BACKGROUND_INTENSITY | FOREGROUND_INTENSITY |
                  BACKGROUND_RED | BACKGROUND_GREEN |
                  BACKGROUND_BLUE |
      FOREGROUND_RED);
    break;
  case 10:    // Green on White
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                 BACKGROUND_INTENSITY | FOREGROUND_INTENSITY |
                 BACKGROUND_RED | BACKGROUND_GREEN |
                 BACKGROUND_BLUE | FOREGROUND_GREEN);
    break;
  case 11:    // Yellow on White
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                 BACKGROUND_INTENSITY | FOREGROUND_INTENSITY |
                 BACKGROUND_RED | BACKGROUND_GREEN |
                 BACKGROUND_BLUE | FOREGROUND_RED |
                 FOREGROUND_GREEN);
    break;
  case 12:    // Blue on White
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                 BACKGROUND_INTENSITY | FOREGROUND_INTENSITY |
                 BACKGROUND_RED | BACKGROUND_GREEN |
                 BACKGROUND_BLUE | FOREGROUND_BLUE);
    break;
  case 13:    // Magenta on White
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                 BACKGROUND_INTENSITY | FOREGROUND_INTENSITY |
                 BACKGROUND_RED | BACKGROUND_GREEN |
                 BACKGROUND_BLUE | FOREGROUND_RED |
                 FOREGROUND_BLUE);
    break;
  case 14:    // Cyan on White
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                 BACKGROUND_INTENSITY | FOREGROUND_INTENSITY |
                 BACKGROUND_RED | BACKGROUND_GREEN |
                 BACKGROUND_BLUE | FOREGROUND_GREEN |
                 FOREGROUND_BLUE);
    break;
  case 15:    // White on White
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                BACKGROUND_INTENSITY | FOREGROUND_INTENSITY |
                BACKGROUND_RED | BACKGROUND_GREEN |
                BACKGROUND_BLUE | FOREGROUND_RED |
                FOREGROUND_GREEN | FOREGROUND_BLUE);
    break;
  default :    // White on Black
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
                FOREGROUND_INTENSITY | FOREGROUND_RED |
                FOREGROUND_GREEN | FOREGROUND_BLUE);
    break;
  }
}

Downloads

Download demo project - 110 Kb
Download source - 7 Kb


Comments

  • is possible this method??

    Posted by Legacy on 02/11/2004 12:00am

    Originally posted by: pegas

    i know console api.
    i wanna execute the ConsoleApp and send the data.
    flow chart is below..

    main program is windows application.
    in main program, createprocess ConsoleApp(exe)
    then, i wanna control the consoleapp in main program.
    But i cant get the handle of ConsoleApp..

    How Method can i...

    Reply
  • Troubles !

    Posted by Legacy on 01/20/2004 12:00am

    Originally posted by: MTJ

    I'm using Visual Basic 5.0, I'm trying to write a console
    
    application in it. I translated the VC++ code into Visual
    Basic format, added "Types" and API Declarations and then
    compiled and changed the App mode to Console User
    Interface. Text printing was all right, text inputing
    worked, but gotoxy() and clrscr() didn't work! What can I
    do now?

    The code below was the code I used:

    Public Type COORD
    x As Integer
    y As Integer
    End Type

    Public Type SMALL_RECT
    Left As Integer
    Top As Integer
    Right As Integer
    Bottom As Integer
    End Type

    Public Type CONSOLE_SCREEN_BUFFER_INFO
    dwSize As COORD
    dwCursorPosition As COORD
    wAttributes As Integer
    srWindow As SMALL_RECT
    dwMaximumWindowSize As COORD
    End Type

    Public Declare Function GetStdHandle Lib "kernel32" Alias "GetStdHandle" _
    (ByVal nStdHandle As Long) As Long

    Private Declare Function WriteFile Lib "kernel32" Alias "WriteFile" _
    (ByVal hFile As Long, ByVal lpBuffer As Any, _
    ByVal nNumberOfBytesToWrite As Long, _
    lpNumberOfBytesWritten As Long, _
    ByVal lpOverlapped As Any) As Long

    Private Declare Function ReadFile Lib "kernel32" Alias "ReadFile" _
    (ByVal hFile As Long, ByVal lpBuffer As Any, _
    ByVal nNumberOfBytesToRead As Long, _
    lpNumberOfBytesRead As Long, _
    ByVal lpOverlapped As Any) As Long

    Public Declare Function GetConsoleScreenBufferInfo Lib "kernel32" _
    (ByVal hConsoleOutput As Long, _
    lpConsoleScreenBufferInfo As CONSOLE_SCREEN_BUFFER_INFO) As Long

    Public Declare Function SetConsoleCursorPosition Lib "kernel32" _
    (ByVal hConsoleOutput As Long, _
    dwCursorPosition As COORD) As Long

    Public Declare Function FillConsoleOutputCharacter Lib "kernel32" _
    Alias "FillConsoleOutputCharacterA" _
    (ByVal hConsoleOutput As Long, _
    ByVal cCharacter As Byte, _
    ByVal nLength As Long, _
    dwWriteCoord As COORD, _
    lpNumberOfCharsWritten As Long) As Long

    Public Declare Function FillConsoleOutputAttribute Lib "kernel32" _
    (ByVal hConsoleOutput As Long, _
    ByVal wAttribute As Long, _
    ByVal nLength As Long, _
    dwWriteCoord As COORD, _
    lpNumberOfAttrsWritten As Long) As Long

    Public Const STD_OUTPUT_HANDLE = -11&
    Public Const STD_INPUT_HANDLE = -10&

    Public Sub clrscr()

    Dim coordScreen As COORD
    coordScreen.x = 0: coordScreen.y = 0
    Dim cCharsWritten As Long
    Dim csbi As CONSOLE_SCREEN_BUFFER_INFO
    Dim dwConSize As Long
    Dim hConsole As Long: hConsole = GetStdHandle(STD_OUTPUT_HANDLE)

    Call GetConsoleScreenBufferInfo(hConsole, csbi)
    dwConSize = csbi.dwSize.x * csbi.dwSize.y
    Call FillConsoleOutputCharacter(hConsole, CByte(Asc(" ")), dwConSize, coordScreen, cCharsWritten)
    Call GetConsoleScreenBufferInfo(hConsole, csbi)
    Call FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, cCharsWritten)
    Call SetConsoleCursorPosition(hConsole, coordScreen)


    End Sub

    '
    ' Moves the cursor to x, y in console window
    ' ie x=left\right y=top\bottom
    '
    Public Sub gotoxy(ByVal x As Integer, ByVal y As Integer)

    Dim point As COORD
    point.x = x: point.y = y
    Call SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), point)

    End Sub

    Reply
  • DOS-Appearance

    Posted by Legacy on 12/12/2003 12:00am

    Originally posted by: Alon Weiss

    I wanted my app to resemble to an old 80x25 DOS program.
    
    Here is how i did it:

    void SetScrnSize(int W, int H)
    {
    SMALL_RECT SR;
    SR.Top = 0;
    SR.Left = 0;
    SR.Bottom = H-1;
    SR.Right = W-1;

    SetConsoleWindowInfo(
    GetStdHandle(STD_OUTPUT_HANDLE),
    TRUE,
    &SR);

    COORD Sz;
    Sz.X = W;
    Sz.Y = H;

    SetConsoleScreenBufferSize(
    GetStdHandle(STD_OUTPUT_HANDLE),
    Sz
    );

    you can call it with 80,25 and it works!
    in console.cpp example, add these lines after the clrscr() call:

    SetScrnSize(80,25);
    for (i=0; i<8;i++)
    {
    for (int j=0;j<9;j++)
    cout<<"-";
    cout<<"|";
    }
    for (i=2;i<=25;i++)
    {
    cout <<i;
    if (i<25) cout <<endl;
    };

    hope it will help someone..
    Alon Weiss.

    Reply
  • may i ask something??

    Posted by Legacy on 11/14/2003 12:00am

    Originally posted by: blue-bon

    i had try the code n it's work...thx
    but somthing bothering me that i dont know what does its statement mean. esp. -SetConsoleTextAtribute-. any one can help me to find out the description for this syntax....


    thx

    Reply
  • Example on Drawing w/the gotoxy function

    Posted by Legacy on 09/01/2003 12:00am

    Originally posted by: Wes Baldwin

    // drawing.cpp : A simple set of drawing functions by Wes Baldwin
    
    //Code date 09.01.03

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

    const unsigned char horiz_line = '�';
    const unsigned char vert_line = '�';
    const unsigned char ul_corner = '�';
    const unsigned char ur_corner = '�';
    const unsigned char ll_corner = '�';
    const unsigned char lr_corner = '�';

    using namespace std;

    void draw_hLine(int length, int x = 0, int y = 0);
    void draw_vLine(int length, int x = 0, int y = 0);
    void draw_Rect(int x, int y, int l, int w);
    void set_Cursor(int x, int y);

    int main(int argc, char* argv[])
    {
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
    FOREGROUND_INTENSITY |
    FOREGROUND_RED); //contributed by Roger McElfresh

    draw_Rect(1, 1, 15, 75);
    draw_Rect(2, 2, 15, 75);
    set_Cursor(15,9);
    cout << "Line and Rectangle Drawing Code by: Wes Baldwin";

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),
    FOREGROUND_INTENSITY |
    FOREGROUND_RED |
    FOREGROUND_GREEN |
    FOREGROUND_BLUE); //contributed by Roger McElfresh

    cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
    return 0;
    }

    void set_Cursor(int x, int y) //contributed by Roger McElfresh
    {
    COORD point;
    point.X = x; point.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), point);
    return;
    }


    void draw_hLine(int length, int x, int y)
    {
    int i = 0;

    if(x > 0 || y > 0)
    set_Cursor(x, y);

    for(i = 0; i < length; i++)
    {
    cout << horiz_line;
    }
    return;
    }

    void draw_vLine(int length, int x, int y)
    {
    int i = 0;

    if(x > 0 || y > 0)
    set_Cursor(x, y);

    for(i = 0; i < length; i++)
    {
    set_Cursor(x, y + i);
    cout << vert_line;
    }
    return;
    }

    void draw_Rect(int x, int y, int l, int w)
    {
    set_Cursor(x, y);
    cout << ul_corner;
    draw_hLine(w - 2);
    cout << ur_corner;
    set_Cursor(x, y + 1);
    draw_vLine(l - 2, x, y + 1);
    set_Cursor(x, y + (l - 1));
    cout << ll_corner;
    draw_hLine(w - 2, x + 1, y + (l - 1));
    cout << lr_corner;
    draw_vLine(l - 2, x + w - 1, y + 1);
    return;
    }

    Reply
  • sizing the console window other than default 80X30

    Posted by Legacy on 08/11/2003 12:00am

    Originally posted by: Adam

    What's the most straighforward way to size the console window programmatically so the code determines the console size when the program is launched.

    Reply
  • Your DEFAULT gray isn't the real DOS-gray

    Posted by Legacy on 08/11/2003 12:00am

    Originally posted by: Lord of the Things

    How can i get back that fine DOS-Gray after using these funcs?
    (Cause your default isn't exactly the same)

    Reply
  • Very Kewl

    Posted by Legacy on 06/07/2003 12:00am

    Originally posted by: Retief

    I just poped in your function for font color into my program..added the windows.h and pow! works great

    thanks a lot

    Reply
  • Can I minimize or hide a console programmatically as well?

    Posted by Legacy on 03/11/2003 12:00am

    Originally posted by: SGL

    I would like to minimize (at least) my console app, but don't see a function which allows this. Any ideas?

    Thanks,
    Steve

    Reply
  • If you want to use this in VC++ 5.0...

    Posted by Legacy on 03/11/2003 12:00am

    Originally posted by: Dan

    A friend and I are sitting here in class and he wanted to use your color thing to create a line of characters in his program that flickers different colors. The problem is, whatever was the last color he chose, the compiler made the entire thing that color. We found though that this problem is solved - so far as we can tell - by using 'printf' instead of 'cout'. I am posting here to let any other VC++ 5.0 users know this, but also to see if anyone has an answer as to why the compiler did this.

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • Live Event Date: October 23, 2014 @ 12:00 p.m. ET / 9:00 a.m. PT Despite the current "virtualize everything" mentality, there are advantages to utilizing physical hardware for certain tasks. This is especially true for backups. In many cases, it is clearly in an organization's best interest to make use of physical, purpose-built backup appliances rather than relying on virtual backup software (VBA - Virtual Backup Appliances). Join us for this eSeminar to learn why physical appliances are preferable to …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds