1

我希望能够在双击项目时将项目的背景更改为红色并使它们保持该颜色,这样我就可以只对 FormClose 上的红色项目做一些事情。(例​​如:OnClose 仅​​删除红色项目)是可以使用标准组件吗?

4

1 回答 1

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;
于 2013-10-14T23:21:06.100 回答