# Changing Fonts

This topic is 2905 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi this is a question regards to changing fonts and font colours etc in C++, i have spent a few days on google and reading through books and have to far only found a few completely different examples of which none seem to make sense or compile for me. I was hoping to be able to do things like this http://www.weiqigao.com/blog/images/turbo-cpp.png formatting wise. I dont believe that it can possibly be as difficult as some of the examples shown seem to be. Can anyone explain it in English for us complete new starters? So how to change the font style, and colour, and how to do all those fancy ascii symbols or lines and boxes etc.

##### Share on other sites
C++ itself doesn't deal with fonts at all and it doesn't deal with colors, text output or graphics. What you do is you include different libraries (DirectX/OpenGL for 3d Graphics, the Window System libraries for operating system functions like TCP-IP networking or opening windows to draw 2d or rendering text) and then call those libraries' functions using their C++ interface to do what you want to do.

Could you give some more details on what you actually want to do?

##### Share on other sites
Ahh, thanks for the reply first off. What im trying to do at the moment as me and a few friends are learning the basics, is just make a very simple program that asks for inputs, displays outputs, using random numbers etc etc.

Basically its a really simple combat system, just 3 types of attack. 1, 2 and 3 which lower the hitpoints of the program by a random number between x and y depending on what attack was used. We are expanding it so include other bits and bobs as it seems to be helping us at the moment to learn things like if statements, loops, variables and output etc etc. So nothing with 2d or 3d graphics as such.

Just literally want to display a welcome screen which is a bit like the turbo c++ welcome screen when you are installing it, that type of thing (only example i could think of sorry.) Then display things like the HP bar of each character in a coloured ascii block or something like the blocks on this http://en.wikipedia.org/wiki/File:Aa_example3.png so i can do a simple '10 block hp bar'

.....and perhaps colour the different parts of the text so things like "you attacked for" is white then "25 damage" is red or something.

Im sorry if this is vague but i am struggling to define what im after. If i cant change the font style then thats ok but there must be a way to display ascii and change the colour of the text easily of cout <<

##### Share on other sites
This is likely to be an OS-specific requirement. See Console Functions on MSDN for a list of the functions you'd use in Windows (for example, SetConsoleTextAttribute can be used to set the text colour).

The special symbols depend on the current code page (set with SetConsoleOutputCP). Code page 850 provides a large number of useful box-drawing symbols.

##### Share on other sites
I don't know how the specific turbo-c++ example was done, but you can use curses for this. The font family is typically set by the terminal however, so there's not much you can do about that.

[Edited by - lightbringer on March 8, 2010 7:08:41 AM]

##### Share on other sites
Sorry i should have also said, im at the stage at the moment where i have pretty much just got past the hello world program (started on thursday). So not a lot of this makes sense to me just yet. Im not sure how to apply it i think is what i am saying.

##### Share on other sites
Quote:
 Original post by SomarlSorry i should have also said, im at the stage at the moment where i have pretty much just got past the hello world program (started on thursday). So not a lot of this makes sense to me just yet. Im not sure how to apply it i think is what i am saying.

Maybe we can entice you to drop C++ and pick up a language that you can be immediately productive in, like Python? What are your long-term goals behind learning C++?

##### Share on other sites
hmm... so I guess your options are either using the console window (check this out on what you can do with it on windows : http://msdn.microsoft.com/en-us/library/ms682073(VS.85).aspx )

or delve into GUI (graphical user interface) programming, which is more complicated at first, but for what you want to do you can probably use a library that already provides you with buttons, scrollbars, text-lists and such. My knowledge considering that is not very up-to-date I'm afraid, but if you are on windows, googling for MFC or Windows Programming tutorials (always assuming that windows is the OS you are developing under) will probably get you started

##### Share on other sites
Quote:
Original post by lightbringer
Quote:
 Original post by SomarlSorry i should have also said, im at the stage at the moment where i have pretty much just got past the hello world program (started on Thursday). So not a lot of this makes sense to me just yet. Im not sure how to apply it i think is what i am saying.

Maybe we can entice you to drop C++ and pick up a language that you can be immediately productive in, like Python? What are your long-term goals behind learning C++?

:) i have a view to pretty much go "all the way" with this as far as game programming is concerned, im not talking about making next gen games or breaking new boundaries or even 'god forbid' making an MMO, we just want to make nice simple fun to play games, but not too simple. Standard RPG's, FPS's RTS's etc etc

We want to eventually start up a full blown game development studio (already have 4 coders and 1 guy for graphics and sound.) When the time comes (hopefully within 10 years) we will attract more people to our cause when we are ready to make our own project, for now i just take it one step at a time with the basics and such. So i just wanted to get down and dirty with C++ as once i have a good enough grasp on it you can pretty much make a computer sing and dance with it. If a company we create fails then at least ill have enough C++ experience to do other things with it.

I would also probably like to learn how to modify existing games engines to produce something worthwhile. I did a lot of research before choosing C++ as the language we would all use and it was mostly thanks to the great resources on this site that made me choose.

What im finding difficult at the moment is how many different ways you can do something but how none of them compile. So far i have found no less than 7 different ways of changing colour on the windows console, and yet none of them i understand at the moment nor do any of them seem to work for me as i am obviously not implementing then correctly.

Is there an easy solution to this? I only want to change the font colour a couple of times in a simple program. Oh and display a block which i think is ascii but im not sure how to do it.

##### Share on other sites
Quote:
 Original post by SomarlI did a lot of research before choosing C++ as the language we would all use and it was mostly thanks to the great resources on this site that made me choose.

Great! Nothing is better than someone who's done their homework :)

Quote:
 Original post by SomarlIs there an easy solution to this? I only want to change the font colour a couple of times in a simple program. Oh and display a block which i think is ascii but im not sure how to do it.

The two solutions already presented in this thread should work for you. The simple one is what benryves described - not much extra is necessary. Curses is more involved - it's basically a graphics library for doing those "DOS windows".

##### Share on other sites
Quote:
Original post by lightbringer
Quote:
 Original post by SomarlI did a lot of research before choosing C++ as the language we would all use and it was mostly thanks to the great resources on this site that made me choose.

Great! Nothing is better than someone who's done their homework :)

Quote:
 Original post by SomarlIs there an easy solution to this? I only want to change the font colour a couple of times in a simple program. Oh and display a block which i think is ascii but im not sure how to do it.

The two solutions already presented in this thread should work for you. The simple one is what benryves described - not much extra is necessary. Curses is more involved - it's basically a graphics library for doing those "DOS windows".

Yeah i am hoping to get stuck into benryves post when i get back from work. I had a quick look earlier and im not sure where to start with it. The setconsoleattributes looks right to me but ill be damned if i know where to put it or what to do with it
for example this:

BOOL WINAPI SetConsoleTextAttribute(
__in HANDLE hConsoleOutput,
__in WORD wAttributes
);

doesnt mean anything to me at this moment in time. As in where to put it, what it means or how i can change colours using it.
A
lso that ascii chart was great, i found the block character i am looking for (amongst other things) but i havent a clue how to use them, -d, -b 2588, 219 doesnt mean anything to me im afraid at the moment. Is there a tutorial knocking about where i can start this off?

Maybe i just havent read enough yet. Ill get stuck in tonight.

Many thanks for the replies so far folks. If anyone has anything more to add id love to hear it, every little helps.

##### Share on other sites
Quote:
 Original post by SomarlYeah i am hoping to get stuck into benryves post when i get back from work. I had a quick look earlier and im not sure where to start with it. The setconsoleattributes looks right to me but ill be damned if i know where to put it or what to do with itfor example this:BOOL WINAPI SetConsoleTextAttribute( __in HANDLE hConsoleOutput, __in WORD wAttributes);doesnt mean anything to me at this moment in time. As in where to put it, what it means or how i can change colours using it.
MSDN is chock full of samples (linked from the SetConsoleTextAttribute page).

Quote:
 Also that ascii chart was great, i found the block character i am looking for (amongst other things) but i havent a clue how to use them, -d, -b 2588, 219 doesnt mean anything to me im afraid at the moment. Is there a tutorial knocking about where i can start this off?
Those are the character codes. The four-digit hex number is the Unicode code point, the row/columns are used to find the hex code for that character in the code page (e.g. 'T' is row 5-, column -4, so has a code of 0x54) and the decimal number is that same code but in, well, decimal (e.g. 0x54 = 84).

##### Share on other sites
Im taking a look at it now, going to do a bit of copy pasting, then messing, then try it in the old standard hello world prog.

Still not sure no the ascii thing though.

Imagine saying "Those are the character codes. The four-digit hex number is the Unicode code point, the row/columns are used to find the hex code for that character in the code page (e.g. 'T' is row 5-, column -4, so has a code of 0x54) and the decimal number is that same code but in, well, decimal (e.g. 0x54 = 84)." to a five year old kid and see what face he pulls :)
Im not five of course but as new as i am to this it pretty much resets the brain to zero. Im going to do more googling on this ascii thing see if i can get it in much more simpler terms. Maybe its not my time to understand it yet, as ive been at this less than a week i probably need more depth on other things before i can read a statement like that and just understand it off the bat.

##### Share on other sites
Ok i might have got way in over my head here. I had a read of all those examples, and tried sniffing round a bit but didnt understand any of it. Dont really like that site for how much support it gives to complete newcomers to the language. Now i managed to determine that i need all this to change a font colour i think but cant seem to get it to compile as it gets stuck right off the bat.

#include <windows.h>  void NewLine(void); void ScrollScreenBuffer(HANDLE, INT);  HANDLE hStdout, hStdin; CONSOLE_SCREEN_BUFFER_INFO csbiInfo;  void main(void) {     LPSTR lpszPrompt1 = "Type a line and press Enter, or q to quit: ";    LPSTR lpszPrompt2 = "Type any key, or q to quit: ";    CHAR chBuffer[256];     DWORD cRead, cWritten, fdwMode, fdwOldMode;     WORD wOldColorAttrs;     // Get handles to STDIN and STDOUT.     hStdin = GetStdHandle(STD_INPUT_HANDLE);     hStdout = GetStdHandle(STD_OUTPUT_HANDLE);     if (hStdin == INVALID_HANDLE_VALUE ||         hStdout == INVALID_HANDLE_VALUE)     {        MessageBox(NULL, TEXT("GetStdHandle"), TEXT("Console Error"),             MB_OK);        return;    }    // Save the current text colors.     if (! GetConsoleScreenBufferInfo(hStdout, &csbiInfo))     {        MessageBox(NULL, TEXT("GetConsoleScreenBufferInfo"),             TEXT("Console Error"), MB_OK);         return;    }    wOldColorAttrs = csbiInfo.wAttributes;     // Set the text attributes to draw red text on black background.     if (! SetConsoleTextAttribute(hStdout, FOREGROUND_RED |             FOREGROUND_INTENSITY))    {        MessageBox(NULL, TEXT("SetConsoleTextAttribute"),             TEXT("Console Error"), MB_OK);        return;    }    // Write to STDOUT and read from STDIN by using the default     // modes. Input is echoed automatically, and ReadFile     // does not return until a carriage return is typed.     //     // The default input modes are line, processed, and echo.     // The default output modes are processed and wrap at EOL.     while (1)     {         if (! WriteFile(             hStdout,               // output handle             lpszPrompt1,           // prompt string             lstrlenA(lpszPrompt1), // string length             &cWritten,             // bytes written             NULL) )                // not overlapped         {            MessageBox(NULL, TEXT("WriteFile"), TEXT("Console Error"),                 MB_OK);             return;        }        if (! ReadFile(             hStdin,    // input handle             chBuffer,  // buffer to read into             255,       // size of buffer             &cRead,    // actual bytes read             NULL) )    // not overlapped         break;         if (chBuffer[0] == 'q') break;     }     // Turn off the line input and echo input modes     if (! GetConsoleMode(hStdin, &fdwOldMode))     {       MessageBox(NULL, TEXT("GetConsoleMode"), TEXT("Console Error"),           MB_OK);        return;    }    fdwMode = fdwOldMode &         ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);     if (! SetConsoleMode(hStdin, fdwMode))     {       MessageBox(NULL, TEXT("SetConsoleMode"), TEXT("Console Error"),           MB_OK);        return;    }    // ReadFile returns when any input is available.      // WriteFile is used to echo input.     NewLine();    while (1)     {         if (! WriteFile(             hStdout,               // output handle             lpszPrompt2,           // prompt string             lstrlenA(lpszPrompt2), // string length             &cWritten,             // bytes written             NULL) )                // not overlapped         {            MessageBox(NULL, TEXT("WriteFile"), TEXT("Console Error"),                 MB_OK);            return;        }        if (! ReadFile(hStdin, chBuffer, 1, &cRead, NULL))             break;         if (chBuffer[0] == '\r')            NewLine();        else if (! WriteFile(hStdout, chBuffer, cRead,             &cWritten, NULL)) break;        else            NewLine();        if (chBuffer[0] == 'q') break;     }     // Restore the original console mode.     SetConsoleMode(hStdin, fdwOldMode);    // Restore the original text colors.     SetConsoleTextAttribute(hStdout, wOldColorAttrs);}// The NewLine function handles carriage returns when the processed // input mode is disabled. It gets the current cursor position // and resets it to the first cell of the next row.  void NewLine(void) {     if (! GetConsoleScreenBufferInfo(hStdout, &csbiInfo))     {        MessageBox(NULL, TEXT("GetConsoleScreenBufferInfo"),             TEXT("Console Error"), MB_OK);         return;    }    csbiInfo.dwCursorPosition.X = 0;     // If it is the last line in the screen buffer, scroll     // the buffer up.     if ((csbiInfo.dwSize.Y-1) == csbiInfo.dwCursorPosition.Y)     {         ScrollScreenBuffer(hStdout, 1);     }     // Otherwise, advance the cursor to the next line.     else csbiInfo.dwCursorPosition.Y += 1;      if (! SetConsoleCursorPosition(hStdout,         csbiInfo.dwCursorPosition))     {        MessageBox(NULL, TEXT("SetConsoleCursorPosition"),             TEXT("Console Error"), MB_OK);         return;    }} void ScrollScreenBuffer(HANDLE h, INT x){    SMALL_RECT srctScrollRect, srctClipRect;    CHAR_INFO chiFill;    COORD coordDest;    srctScrollRect.Left = 0;    srctScrollRect.Top = 1;    srctScrollRect.Right = csbiInfo.dwSize.X - x;     srctScrollRect.Bottom = csbiInfo.dwSize.Y - x;      // The destination for the scroll rectangle is one row up.      coordDest.X = 0;     coordDest.Y = 0;      // The clipping rectangle is the same as the scrolling rectangle.     // The destination row is left unchanged.      srctClipRect = srctScrollRect;      // Set the fill character and attributes.      chiFill.Attributes = FOREGROUND_RED|FOREGROUND_INTENSITY;     chiFill.Char.AsciiChar = (char)' ';      // Scroll up one line.      ScrollConsoleScreenBuffer(         h,               // screen buffer handle         &srctScrollRect, // scrolling rectangle         &srctClipRect,   // clipping rectangle         coordDest,       // top left destination cell         &chiFill);       // fill character and color }

[Please don't just dump code here. Learn to use [code] or [source] tags as appropriate. -Zahlman]

Is this right? Do i include this in any code i want to get the font colour to change? If so where do i implement the folt change now to something like cout << ?

Btw bare in mind i know not one line of this except the include bit right at the top, the void main(void) bit and the bits where it says return;
So is all this necessary to change the font colour? If so is there a better guide as to how to understand each line of this code peice by peice? Also how come this doesnt compile in dev c++, i did copy paste but i know by now that that doesnt always (actually rarely) works and always comes up with strange errors a poor newcomer could never possibly understand. I just need a little (or big) push here.

Think of it like explaining how to do something simple on a car but to someone who doesnt even know what an exhaust is and has barely mastered that a car traditionally has 4 wheels but doesnt really understand why it has 4 wheels yet.

[Edited by - Zahlman on March 8, 2010 6:20:38 PM]

##### Share on other sites
Quote:
 Original post by SomarlOk i might have got way in over my head here. I had a read of all those examples, and tried sniffing round a bit but didnt understand any of it. Dont really like that site for how much support it gives to complete newcomers to the language.
It's nothing to do with the language, as such; it's the Win32 API, and can be used from just about any programming language. Here's a simpler example:

#include <iostream>#include <windows.h>int main() {	// To control the console output we generally need a "handle" to it.	// Use GetStdHandle to retrieve this handle.	HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);		// Check that the handle is valid.	if (hStdout == INVALID_HANDLE_VALUE) {		// Something went wrong - bail out!		std::cout << "Could not retrieve console output handle." << std::endl;		return 1;	}	// Set the colour to bright red.	if (!SetConsoleTextAttribute(hStdout, FOREGROUND_RED | FOREGROUND_INTENSITY)) {		// Something went wrong - bail out!		std::cout << "Could not set text attribute." << std::endl;		return 1;	}	// Output some text.	std::cout << "This text is bright red." << std::endl;	// To output a special (non-ASCII) character, we must first ensure we're using the correct code page.	// Code page 850 has a lot of useful box-drawing characters in it, so let's use that.	if (!SetConsoleOutputCP(850)) {		// Something went wrong - bail out!		std::cout << "Could not set output code page attribute." << std::endl;		return 1;	}	// The 50% dither pattern is character code 0xB1	std::cout << (char)0xB1 << std::endl;}

Quote:
 Also how come this doesnt compile in dev c++
Why you shouldn't use Dev-C++. However, I can't tell you much more without you providing the error messages that Dev-C++ produces.

##### Share on other sites
I have managed to make it work using something similar to this then just changing the colour using setcolour (number to change colour) etc. Its nice and simple and it works for now. I suppose end goal i wont be using things like this. As has been said before i will have to use things from directx 3d and such to create fonts and colour etc, i just wanted a simple way of changing it to liven up what we were doing at the moment and this works. Problem solved i think. However i still cant seem to manipulate the background colour to anything from black.

Oh and because of this thread i am going to stop using dev c++ and look for an alternative thanks to that interesting (and somewhat damning) read. I like the look of visual and can afford it but it seems overly complicated for a complete newcomer so i may start off with blocks instead. Are there any other alternatives out there i should consider?

##### Share on other sites
Quote:
 Original post by SomarlOh and because of this thread i am going to stop using dev c++ and look for an alternative thanks to that interesting (and somewhat damning) read. I like the look of visual and can afford it but it seems overly complicated for a complete newcomer so i may start off with blocks instead. Are there any other alternatives out there i should consider?
Visual C++ Express is free and contains everything you'll need for a while. It's not that complicated, it's the most used compiler / IDE on these forums (so plenty of people should be able to help you out), and is what the professionals generally use for Windows (And some non-Windows) development.

• 9
• 10
• 12
• 10
• 10