Mega Code Archive

 
Categories / Delphi / VCL
 

Showing highlighted text in a ListBox

Title: Showing highlighted text in a ListBox Question: How to show highlighted text in a ListBox? Answer: This example shows how to highlight a text in a ListBox. To do this, Add a TListBox and TEditBox components to the form. ---- In the form's PRIVATE section enter: HighlightText : string ; TextLength : integer ; Foreground : TColor ; Background : TColor ; ---- And another events of the Form1,ListBox1 and 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//if you want to seek a text... HighlightText := Edit1.Text ; TextLength := Length(Edit1.Text) ; ListBox1.Refresh ; end; procedure TForm1.FormCreate(Sender: TObject); begin Edit1.Clear; ListBox1.Items.LoadFromFile('c:\Autoexec.bat');//you can change it. ListBox1.Style:=lbOwnerDrawFixed; HighlightText := Edit1.Text ; TextLength := 4 ; Background := clRed ; Foreground := clWhite ; end;