delphicolorsrichedit

Change RichEdit text colour independently with text already loaded


How can I change the text color of a Rich Edit line by line? It is dependent on the position. First line must be red, second green and so forth. The problem is the text of the Rich Edit is already loaded in. So it must be changed after the text is already in the control. I am using Delphi.


Solution

  • It is better to load it with the right colours from the beginning.

    But to answer your question, a quick and dirty and rather ugly solution is to do

    function RandomColor: TColor;
    begin
      Result := RGB(Random(256), Random(256), Random(256))
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    var
      i: Integer;
    begin
      for i := 0 to RichEdit1.Lines.Count - 1 do
      begin
        RichEdit1.CaretPos := Point(0, i);
        RichEdit1.SelLength := RichEdit1.Lines[i].Length;
        RichEdit1.SelAttributes.Color := RandomColor;
      end;
    end;