Title: Highlight selected item with a different color in ListBox
Question: A way to highlight selected item in different color.
Answer:
sometimes you want a way to highlight selected item with a different color in List Box for instance, put this code in OnClick Event to make the effect,with enhanced client wither:
procedure TMainForm.ListBoxClick(Sender: TObject);
var
NewWidth:integer;
begin
with ListBox do
begin
//if the string item is wider than the List Box
if (Canvas.TextWidth(Items[ItemIndex])+25 {for offset reason})
ListBox.Width then
begin
//calculate the new width
NewWidht := Canvas.TextWidth(Items[ItemIndex])+8;
//send message the List Box the add a
//horizontal scroll bar to view the contenet
SendMessage(ListBox.Handle ,
// horizontal scroll bar message flag
LB_SETHORIZONTALEXTENT,
//set the new width
NewWidht
, 0);
end
else
//calculate the width
NewWidht := Canvas.TextWidth(Items[ItemIndex])
//put the color as you like or put a conditional code
//and pass the color parameter
Canvas.Brush.Color:=clGreen;
Canvas.Pen.Color:=.Brush.Color;
//highlight the item
Canvas.FillRect(Rect(ItemRect(ItemIndex).Left,
ItemRect(ItemIndex).Top,
ItemRect(ItemIndex).Right+NewWidht,
ItemRect(ItemIndex).Bottom));
//wright the text
Canvas.TextOut(ItemRect(ItemIndex).Left,
ItemRect(ItemIndex).Top,
Items[ItemIndex])
end
end;