Search code examples
user-interfacelazarusrichtext

How to prevent TRichMemo from resetting text attributes when you add new text


I have a TRichMemo object which I create and populate with text at runtime.

I have a timer that triggers a function each 10 seconds. The function looks something like this:

procedure TServerSideForm.NewLineTimerTimer(Sender: TObject);
var
  timeForward: TDateTime;

  timerText: wideString;

  startRange, endRange: longInt;
begin
  timeForward := Time;
  timeForward := IncSecond(timeForward, ServerSideForm.NewLineTimer.Interval div 1000);

  //...

  timerText := TimeToStr(Time) + ' - ' + TimeToStr(timeForward);   


  startRange := Length(WindowMemo.Text);

  WindowMemo.Text := WindowMemo.Text + sLineBreak + sLineBreak + timerText + sLineBreak + sLineBreak;

  endRange := Length(WindowMemo.Text) - 1;


  WindowMemo.SetRangeColor(startRange, endRange, clGreen);

  //...
end;    

Everything works perfectly, text in the desired range becomes green.

But as soon as I add some new text to my TRichMemo, everything resets back to black text.

Why is this happening? Is there a way to prevent this reset from happening?

P.S Same situation happens, when I use the SetRangeParams function.


Solution

  • Use Append method instead of accessing a type String value Text as it keeps only the literals not the format.

    Change

    WindowMemo.Text := WindowMemo.Text + sLineBreak + sLineBreak + timerText + sLineBreak + sLineBreak;
    

    with

    WindowMemo.Append(sLineBreak + sLineBreak + timerText + sLineBreak + sLineBreak); 
    

    METHOD 2

    Should you decide to add text withot line breaks you can replace the mentioned line with

    uses RichMemoUtils;
    ...    
    InsertColorStyledText(WindowMemo,timerText,Random($FFFFFF),[],Length(WindowMemo.Text) -1);