Console applications are not of entertaining type. They have that whitish dull color in a black background. But who says you cannot change it! Here is a tip to change the text color of console programs.
Console programs written by any language uses the default color to show text. Which is white on black background. It is the usual color for any program written in Free Pascal as well. But what if you need to change it? What if you want to highlight the results of your program with a different color to separate it from other text? We have an option.
How…?
With the crt
unit you can do many cool tricks to your dull boring good old console programs. You can look here for many tricks. We don’t need all of these for now. We will only focus on changing Text Color and yes, background color as well.
We have 2 procedures to change text and background colors of Free Pascal console programs, TextColor and TextBackground.
How to change Text Color in Free Pascal
We have a procedure for changing text color in Free Pascal, which is TextColor()
. Check out the syntax below:
1 | procedure TextColor( |
You can use something like TextColor(Red);
before a Write
or WriteLn
function to print text with the Red color. Like this:
1 | TextColor(Red); |
But this procedure is in the crt
unit. So you will have to add it in the uses
clause:
1 | uses |
Color constants are as follows:
1 | Black = 0; |
A simple program example can be given below:
1 | Program ExampleTextColor; |
You can try this code with Lazarus by Creating a new Program Project (Project -> New Project -> Program -> OK) then selecting all text and pasting (replacing) the code. You can then Run the code (F9 or Run -> Run).
How to change the background color in Free Pascal
We can also change the background color of text in Free Pascal console programs. We can use the TextBackground()
procedure to do this job, which is also from crt
unit. Look at the syntax:
1 | procedure TextBackground( |
The color constants are same as mentioned above.
You can easily change the background of printed text on the console screen. You will have to use TextBackground
before any Write
or WriteLn
code. Like this:
1 | TextBackground(Green); |
A sample program code example can be like this:
1 | Program ExampleBgColor; |
You can try the above code with a New Program Project in Lazarus, like stated above.
Ref:
http://www.math.uni-leipzig.de/pool/tuts/FreePascal/units/node2.html
http://www.freepascal.org/docs-html/rtl/crt/textcolor.html
http://www.freepascal.org/docs-html/rtl/crt/textbackground.html
Downloads
You can download the source code for the tutorial project and executable/EXE files from the links below: