Click here to Skip to main content
Click here to Skip to main content

Coloured Error Messages for Console Applications

, 5 Dec 2006 CPOL
Rate this:
Please Sign up or sign in to vote.
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. 

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:

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)

Share

About the Author

Prateek Kumar Dubey
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 PinmemberYacha13-Dec-06 21:52 
Generalrestore original colors Pinmemberosy6-Dec-06 0:03 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141216.1 | Last Updated 6 Dec 2006
Article Copyright 2006 by Prateek Kumar Dubey
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid