Click here to Skip to main content
13,049,814 members (63,750 online)
Click here to Skip to main content
Add your own
alternative version


18 bookmarked
Posted 5 Dec 2006

Coloured Error Messages for Console Applications

, 5 Dec 2006
Rate this:
Please Sign up or sign in to vote.
Implementation of a function which will print coloured messages on console window


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 ;
    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 | 
        return 0;
    nBuf = _tprintf(_T("%s"),szBuffer) ;
    //restore to white.
    if (! SetConsoleTextAttribute(hStdout, FOREGROUND_RED |
        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..!


  • 5th December, 2006: Initial post


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


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 | :)

You may also be interested in...


Comments and Discussions

Generalmore perfect idea Pin
Yacha13-Dec-06 20:52
memberYacha13-Dec-06 20:52 
Generalrestore original colors Pin
osy5-Dec-06 23:03
memberosy5-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.

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