Formatting Lines in Rich Edit Using Delphi's SelText & SelStart

Add Formatted (Color, Style, Font) Lines to TRichEdit

Formatted Lines in RichEdit using Delphi's SelText and SelStart
Formatted Lines in RichEdit using Delphi's SelText and SelStart.

The TRichEdit Delphi control is a wrapper for a Windows rich text edit control. You can use a Rich Edit control to display and edit RTF files.

While you can create nice user interface "around" the Rich Edit control with toolbar buttons to set and change text display attributes, adding formatted lines to Rich Edit programmatically is fairly cumbersome - as you will see.

How to Add Formatted Lines to Rich Edit

To create bold text from a selection of text displayed in the Rich Edit control, at runtime, you need to make a section of text and then set the selection's properties to SelAttributes.

However, what if you're not dealing with a selection of text and instead want to add (append) formatted text to a Rich Edit control? You might think Lines property can be used to add bold or colored text to Rich Edit. However, Lines is a simple TStrings and will accept only plain, unformatted text.

Don't give up - of course there's a solution.

Look at this example for some help:

 //richEdit1 of type TRichEdit
 with richEdit1 do
   //move caret to end
   SelStart := GetTextLen;
   //add one unformatted line
   SelText := 'This is the first line' + #13#10;
   //add some normal font text
   SelText := 'Formatted lines in RichEdit' + #13#10;
   //bigger text
   SelAttributes.Size := 13;
   //add bold + red
   SelAttributes.Style := [fsBold];
   SelAttributes.Color := clRed;
   SelText := 'About';
   //only bold
   SelAttributes.Color := clWindowText;
   SelText := ' Delphi ';
   //add italic + blue
   SelAttributes.Style := [fsItalic];
   SelAttributes.Color := clBlue;
   SelText := 'Programming';
   //new line
   SelText := #13#10;
   //add normal again
   SelAttributes.Size := 8;
   SelAttributes.Color := clGreen;
   SelText := 'think of AddFormattedLine custom procedure...';

To start, move the caret to the end of the text in the Rich Edit. Then, apply formatting before you actually append the new text.

More tips on Delphi applications: