Author: Jonas Bilinkevicius
Do you want to have a nice looking rich edit?
Answer:
This procedure will search and change the attributes (font name, font size, font
color, font style, and back color) of certain words inside a rich edit control.
Try the example.
1 type
2 TTextAttributes = record
3 Font: TFont;
4 BackColor: TColor;
5 end;
6 {..}
7
8 procedure SetTextColor(oRichEdit: TRichEdit; sText: string; rAttributes:
9 TTextAttributes);
10 var
11 iPos: Integer;
12 iLen: Integer;
13
14 Format: CHARFORMAT2;
15 begin
16 FillChar(Format, SizeOf(Format), 0);
17 Format.cbSize := SizeOf(Format);
18 Format.dwMask := CFM_BACKCOLOR;
19 Format.crBackColor := rAttributes.BackColor;
20
21 iPos := 0;
22 iLen := Length(oRichEdit.Lines.Text);
23 iPos := oRichEdit.FindText(sText, iPos, iLen, []);
24
25 while iPos <> -1 do
26 begin
27 oRichEdit.SelStart := iPos;
28 oRichEdit.SelLength := Length(sText);
29 oRichEdit.SelAttributes.Color := rAttributes.Font.Color;
30 oRichEdit.SelAttributes.Size := rAttributes.Font.Size;
31 oRichEdit.SelAttributes.Style := rAttributes.Font.Style;
32 oRichEdit.SelAttributes.Name := rAttributes.Font.Name;
33
34 oRichEdit.Perform(EM_SETCHARFORMAT, SCF_SELECTION, Longint(@Format));
35
36 iPos := oRichEdit.FindText(sText, iPos + Length(sText), iLen, []);
37 end;
38 end;
39
40 Example:
41
42 var
43 rAttrib: TTextAttributes;
44 begin
45 rAttrib.Font := TFont.Create;
46 rAttrib.Font.Color := clWhite;
47 rAttrib.Font.Size := 16;
48 rAttrib.Font.Style := [fsBold];
49 rAttrib.BackColor := clRed;
50
51 SetTextColor(RichEdit1, 'Delphi', rAttrib);
52
53 //Change another word attributes.
54 rAttrib.Font.Color := clYellow;
55 rAttrib.Font.Size := 10;
56 rAttrib.Font.Style := [fsBold, fsItalic];
57 rAttrib.BackColor := clBlue;
58
59 SetTextColor(RichEdit1, 'Is greate', rAttrib);
60
61 rAttrib.Font.Free; //Now free the font.
62 end;
|