6

I'm using a TRichEdit in order to show the last operations that have been done in my application. The first line of my TRichEdit should be the last operation. If the operation failed, I would like to put this line in red.

My problem is that I am not able to insert a colored line at the top of my TRichEdit. Here is what I've tried:

RichEditLog.SelAttributes.Color := clBlack;
RichEditLog.Lines.Insert(0, 'Operation 1 OK');
// RichEditLog.Lines.Add('Operation 1 OK');

RichEditLog.SelAttributes.Color := clRed;
RichEditLog.Lines.Insert(0, 'Operation 2 failed');
// RichEditLog.Lines.Add('Operation 2 failed');

RichEditLog.SelAttributes.Color := clRed;
RichEditLog.Lines.Insert(0, 'Operation 3 failed');
// RichEditLog.Lines.Add('Operation 3 failed');

RichEditLog.SelAttributes.Color := clBlack;
RichEditLog.Lines.Insert(0, 'Operation 4 OK');
// RichEditLog.Lines.Add('Operation 4 OK');

The problem is that my TRichEdit only apply the first change of color and keep it for all the lines. If I use Add() instead of Insert(), the colors are changing but the line are inserted at the end of my TRichEdit.

My question is : Is there an easy way to get the results I'm looking for ?

Aleph0
  • 470
  • 2
  • 10
  • 27

2 Answers2

5

You need to set the selected start and length to 0 if you want to insert at the beginning:

RichEditLog.SelStart := 0;
RichEditLog.SelLength := 0;
RichEditLog.SelAttributes.Color := clBlack;
RichEditLog.Lines.Insert(0, 'Operation 1 OK');

Alternatively, instead of RichEditLog.Lines.Insert() you can assign the text to RichEdit.SelText, but then you need to add the new line characters yourself, f.ex.:

RichEditLog.SelText := 'Operation 1 OK'+sLineBreak;

Either way, when applied to your test code the result is:

enter image description here

Tom Brunberg
  • 20,312
  • 8
  • 37
  • 54
1

Did you try playing with SelAttributes and SelText, SelStart, SelLenght ?

Insert(0,'This is blue text.');
RichEdit1.SelStart := 0; 
RichEdit1.SelLenght := //end;
RichEdit1.SelAttributes.Color := clBlue;
cristallo
  • 1,951
  • 2
  • 25
  • 42
  • I tried to use `SelAttributes` as showed in my question but it only works if I use `Lines.Add` but doesn't work if I use `Lines.Insert`. The color changes once and never change anymore after that. – Aleph0 Nov 04 '16 at 12:49
  • I am suggesting you to insert not formatted line using `Insert ` and then using `SelStart`, `SelLength` for applying the style to the selected text – cristallo Nov 04 '16 at 12:52
  • Thank you, I used Tom's answer but it looks similar to your answer. ;) – Aleph0 Nov 04 '16 at 12:59
  • 2
    yes ... his code is more correct, I was not using real Delphi compiler ... but only my mind and memory :-) – cristallo Nov 04 '16 at 13:01