Click here to Skip to main content
15,885,767 members
Articles / Programming Languages / C++

Coloured Error Messages for Console Applications

Rate me:
Please Sign up or sign in to vote.
4.26/5 (16 votes)
5 Dec 2006CPOL 27.3K   18   2
Implementation of a function which will print coloured messages on console window

Introduction

While working with console applications, sometimes we want to print coloured error messages. Here is the implementation of a very small function which will help in accomplishing the task. 

C++
int _teprintf(TCHAR *format, ...) 
{
    HANDLE hStdOut = NULL ;
    TCHAR szBuffer[1024] ;
    va_list arg_list ;
    int nBuf = 0 ;
    va_start(arg_list,format);
    nBuf = _vsntprintf(szBuffer,1024,format,arg_list) ;
    va_end(arg_list) ;
    //get console output handle
    hStdout = GetStdHandle(STD_OUTPUT_HANDLE);    
    if(!hStdout) {
        return 0;
    }
    //set red colour
    if (! SetConsoleTextAttribute(hStdout, FOREGROUND_RED | 
        FOREGROUND_INTENSITY)) {
        return 0;
    }
    //print 
    nBuf = _tprintf(_T("%s"),szBuffer) ;
    //restore to white.
    if (! SetConsoleTextAttribute(hStdout, FOREGROUND_RED |
        FOREGROUND_BLUE | 
        FOREGROUND_GREEN)) {
        return 0;
    }
    return nBuf ;
}

You can use it as follows:

C++
int _tmain(int argc, _TCHAR* argv[])
{
	_teprintf(_T("\nI am Error\n")) ;
	_tprintf(_T("\nI am Normal\n")) ;
	return 0;
}

Though this is trivial, it is fun..!

History

  • 5th December, 2006: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Other Microsoft
India India
I am currently working with Microsoft at Bangalore (India). My interest lies in areas of generic C++ and windows development. Apart from office hours I try to develop new and useful small tools.
Well, I still feel that I need to be more serious..!
Smile | :)

Comments and Discussions

 
Generalmore perfect idea Pin
Yacha13-Dec-06 20:52
Yacha13-Dec-06 20:52 
Generalrestore original colors Pin
osy5-Dec-06 23:03
osy5-Dec-06 23:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.