1. Computing

Formatting Lines in Rich Edit using Delphi's SelText and SelStart

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

By

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 programmaticaly is fairly cumbersome - as you will see.

Adding Formatted Lines to RichEdit

To make a selection of text displayed in the rich edit control bold you, at run-time, need to select a section of text and set properties to the SelAttributes property.

But what if you *do not have* a section of text to select? What if you 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" text.

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

Here's an example .. go line by line .. and you'll get the look as seen on the screen shot image...

 //richEdit1 of type TRichEdit
 with richEdit1 do
 begin
   //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...';
 end;
 
To start, move the caret to the end of the text in the rich edit. Then apply formatting before you actually apend new text...

Delphi tips navigator:
» No Main Form Delphi Application
« Custom Drawing of TListView Items - Font, Colors, Graphics

©2014 About.com. All rights reserved.