转贴 :
在ListBox中高亮度显示文本
要实现这个例子,你需要在Form上加入一个TListBox和TEditBox构件。
----
在Form的PRIVATE部分输入:
HighlightText : string
TextLength : integer
Foreground : TColor
Background : TColor
----
以下是Form1,ListBox1和EditBox1的事件代码:
procedure TForm1.ListBox1DrawItem(Control: TWinControl
Index: Integer;
Rect: TRect
State: TOwnerDrawState);
var
Location : integer
s : string
Text : string;
ax : integer
TextWidth : integer
OldBrushColor : TColor
OldFontColor : TColor
const
HighlightColor = clRed
begin
with (Control as TListBox) do begin
Canvas.FillRect(Rect)
Location := Pos(HighlightText, Items[Index])
if Location > 0 then begin
TextWidth := Canvas.TextWidth(HighlightText)
s := Items[Index]
ax := 0
while Location > 0 do begin
Text := Copy(s, 1, Location - 1)
s := Copy(s, Location + TextLength, Length(s))
Canvas.TextOut(ax, Rect.Top, Text)
Inc(ax, Canvas.TextWidth(Text))
OldBrushColor := Canvas.Brush.Color
OldFontColor := Canvas.Font.Color
Canvas.Brush.Color := Background
Canvas.Font.Color := Foreground
Canvas.TextOut(ax, Rect.Top, HighlightText)
Canvas.Brush.Color := OldBrushColor
Canvas.Font.Color := OldFontColor
Inc(ax, TextWidth)
Location := Pos(HighlightText, s)
end
Canvas.TextOut(ax, Rect.Top, s)
end
else
Canvas.TextOut(Rect.Left, Rect.Top, Items[Index])
end
end;
procedure TForm1.Edit1Change(Sender: TObject);
begin//如果你想查找文本...
HighlightText := Edit1.Text
TextLength := Length(Edit1.Text)
ListBox1.Refresh
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Edit1.Clear;
ListBox1.Items.LoadFromFile('c:/Autoexec.bat');//你可以改变这里
ListBox1.Style:=lbOwnerDrawFixed;
HighlightText := Edit1.Text
TextLength := 4
Background := clRed
Foreground := clWhite
end;