Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Coloured Error Messages for Console Applications

4.26/5 (16 votes)
5 Dec 2006CPOL 1  
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)