Advertisement
raava403

changeSubStrFontColor in TRichEdit Delphi

Aug 27th, 2019
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 1.61 KB | None | 0 0
  1. {
  2. changeSubStrFontColor in TRichEdit
  3. coded by: uragiristereo on august 28th, 2019
  4. usage example:
  5.   resetStrFontColor(RichEdit1, clBlack);
  6.                     ^TRichedit ^TColor
  7.   changeSubStrFontColor(RichEdit1, Edit1.Text, clRed);
  8.                         ^TRichedit ^TEdit.Text ^TColor
  9. }
  10.  
  11. function subStrCount(const subStr: string; const str: string): Integer;
  12. begin
  13.   if (Length(subStr)=0) or (Length(str)=0) or (Pos(subStr, str)=0) then
  14.     Result:=0
  15.   else
  16.     Result:=(Length(str)-Length(StringReplace(str, subStr, '', [rfReplaceAll]))) div Length(subStr);
  17. end;
  18.  
  19. function xPos(const subStr: string; const str: string; start: integer): Integer;
  20. var
  21.   s: String;
  22. begin
  23.   s:=Copy(str, start-1, Length(str));
  24.   Result:=Pos(subStr, s)+start-1;
  25. end;
  26.  
  27. procedure resetStrFontColor(const richEdit: TRichEdit; const color: TColor);
  28. var
  29.   lastPos: Integer;
  30. begin
  31.   lastPos:=richEdit.SelStart;
  32.   richEdit.SelStart:=0;
  33.   richEdit.SelLength:=Length(richEdit.Text);
  34.   richEdit.SelAttributes.Color:=color;
  35.   richEdit.SelStart:=lastPos;
  36. end;
  37.  
  38. procedure changeSubStrFontColor(const richEdit: TRichEdit; const str: String; const color: TColor);
  39. var
  40.   x, y, lastPos: Integer;
  41. begin
  42.   y:=0;
  43.   lastPos:=richEdit.SelStart;
  44.   try
  45.     for x:=1 to subStrCount(str, richEdit.Text) do begin
  46.       if x=1 then
  47.         richEdit.SelStart:=xPos(str, richEdit.Text, y)
  48.       else
  49.         richEdit.SelStart:=xPos(str, richEdit.Text, y)-2;
  50.       richEdit.SelLength:=length(str);
  51.       richEdit.SelAttributes.Color:=color;
  52.       y:=richEdit.SelStart+length(str)+2;
  53.     end;
  54.   finally
  55.   richEdit.SelStart:=lastPos;
  56.   end;
  57. end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement