双击时,Delphi在列表框中更改项目背景

时间:2013-10-14 23:05:09

标签: delphi listbox delphi-xe2

我希望能够将项目的背景更改为红色,并使它们保持双色,并使它们保持这种颜色,这样我就可以在FormClose上只使用红色的那些。(例如:OnClose只删除红色项目)标准组件可以吗?

1 个答案:

答案 0 :(得分:2)

您需要拥有者绘制ListBox。将其Style属性设置为lbOwnerDrawlbOwnerDrawVariablelbVirtualOwnerDraw,然后使用其OnDrawItem事件绘制您想要的项目(在这种情况下)在lbOwnerDrawVariable中,您还必须提供OnMeasureItem事件处理程序。您必须跟踪哪些项目已被双击,然后您可以以不同于其他项目的方式绘制这些项目。例如:

type
  MyItem = record
    Text: String;
    DblClicked: Boolean;
  end;

MyItems: array of MyItem;

var
  Item: MyItem;
begin
  SetLength(MyItems, ...);

  MyItems[0].Text := 'Item Text';
  MyItems[0].DblClicked := False;

  ...

  for Item in MyItems do
    ListBox1.Items.Add(Item.Text);
end;

procedure TForm1.ListBox1DblClick(Sender: TObject);
var
  Pos: DWORD;
  Pt: TPoint;
  Index: Integer;
begin
  Pos := GetMessagePos;
  Pt.X := Smallint(LOWORD(Pos));
  Pt.Y := Smallint(HIWORD(Pos));
  Index := ListBox1.ItemAtPos(ListBox1.ScreenToClient(Pt), True);
  if Index <> -1 then
  begin
    MyItems[Index].DblClicked := True;
    ListBox1.Invalidate;
  end;
end;

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
  if MyItems[Index].DblClicked then
  begin
    ListBox1.Canvas.Brush.Color := clRed;
    ListBox1.Canvas.Font.Color := clWhite;
  end else
  begin
    ListBox1.Canvas.Brush.Color := ListBox1.Color;
    ListBox1.Canvas.Font.Color := ListBox1.Font.Color;
  end;
  ListBox1.Canvas.FillRect(Rect);
  ListBox1.Canvas.TextRect(Rect, Rect.Left + 2, Rect.Top + 2, MyItems[Index].Text);
end;