Perhaps this approach will do what you want? I think I had the same
functional problem that you had. I wanted to allow different words to have
different color backgrounds in a TMemo.
First, I used a TPanel to hold the words (not a TMemo). Then I created, on
the fly, a TLabel for each word, carefully placing each TLabel in the right
place.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Panel1 : TPanel;
Edit1 : TEdit;
Label1 : TLabel;
Button1 : TButton;
procedure Button1Click(Sender : TObject);
procedure ClearWords;
procedure FormCreate(Sender : TObject);
procedure FormDestroy(Sender : TObject);
procedure PostSentence;
procedure WordClick(Sender : TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1 : TForm1;
Words : array of TLabel;
Sentence : tstringlist;
implementation
{$R *.DFM}
procedure TForm1.ClearWords;
var i : integer;
begin
for i := 0 to Sentence.count - 1 do
Words[i].free;
Sentence.clear;
end;
procedure TForm1.PostSentence;
var i, l, pantop, panleft : integer;
begin
pantop := 6;
panleft := 8;
with Sentence do
SetLength(Words, Sentence.count);
for i := 0 to Sentence.count - 1 do begin
Words[i] := TLabel.create(Panel1);
with TLabel(Words[i]) do begin
Parent := Panel1;
caption := Sentence[i];
OnClick := WordClick;
tag := i mod 5;
l := Canvas.TextWidth(caption);
width := l + 6;
if panleft + l > Panel1.width then begin
Panleft := 10;
pantop := pantop + 15;
end;
left := PanLeft;
top := PanTop;
PanLeft := PanLeft + width;
end;
end;
end;
procedure TForm1.Button1Click(Sender : TObject);
var i : integer; word : string;
begin
ClearWords;
word := '';
for i := 1 to length(Edit1.text) do
if edit1.text[i] = ' ' then begin
Sentence.add(word);
word := '';
end
else
word := word + edit1.text[i];
if word <> '' then
Sentence.add(word); { pick up the last word }
PostSentence;
end;
procedure TForm1.FormCreate(Sender : TObject);
begin
Sentence := tstringlist.create;
end;
procedure TForm1.FormDestroy(Sender : TObject);
begin
ClearWords;
Sentence.free;
end;
procedure TForm1.WordClick(Sender : TObject);
const DarkColorSet : set of 1..10 = [2, 3, 4];
begin
with TLabel(Sender) do begin
case tag of
0 : color := clYellow;
1 : color := clRed;
2 : color := clNavy;
3 : color := clblack;
4 : color := clgreen;
end;
if tag in DarkColorSet then
Font.color := clwhite;
end;
end;
end.