单击此项目时更改ListBox项目的颜色

use*_*068 1 delphi delphi-7

所以我在表单上有一个ListBox,它由不同的链接组成,所有这些都是蓝色和下划线(如html链接,你知道).当用户单击其中一个Items(链接)时,它会在默认浏览器中打开,但我也希望该特定链接将颜色更改为紫色.这是我现在OnClick程序中的内容:

procedure TForm1.ListBox1Click(Sender: TObject);

begin
ShellExecute(Handle, 'open', PAnsiChar(ListBox1.Items[ListBox1.ItemIndex]), nil, nil, SW_SHOWNORMAL);
end;
Run Code Online (Sandbox Code Playgroud)

Dav*_*nan 7

您的问题归结为如何使用不同的字体设置为每个项目绘制列表.您需要执行以下操作:

  1. Style列表框的属性设置为lbOwnerDrawFixed.
  2. 处理OnDrawItem列表框的事件以绘制每个项目.

您的OnDrawItem活动将以字体绘制项目,以指示该项目是否已被点击.你可以管理我认为的逻辑.我将展示一个简单的示例,根据项目的不同来绘制项目Index.

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
  Rect: TRect; State: TOwnerDrawState);
var
  ListBox: TListBox;
  Canvas: TCanvas;
begin
  ListBox := Control as TListBox;
  Canvas := ListBox.Canvas;

  // clear the destination rectangle
  Canvas.FillRect(Rect);

  // prepare the font style and color
  Canvas.Font.Style := [fsUnderline];
  if Odd(Index) then
    Canvas.Font.Color := clBlue
  else
    Canvas.Font.Color := clPurple;

  // draw the text
  Canvas.TextOut(Rect.Left, Rect.Top, ListBox.Items[Index]);

  // and the focus rect
  if odFocused in State then
    Canvas.DrawFocusRect(Rect);
end;
Run Code Online (Sandbox Code Playgroud)