如何在Delphi XE中将背景图像设置为TListview?

时间:2010-10-21 12:39:15

标签: delphi delphi-xe tlistview

如何在Delphi XE中将背景图像设置为TListview?

我想创建一个像Windows资源管理器一样的应用程序。

2 个答案:

答案 0 :(得分:8)

要在列表视图中设置水印,您需要使用LVM_SETBKIMAGE消息,并且需要覆盖TListView的默认WM_ERASEBKGND消息。列表视图取得了位图句柄的所有权,因此您需要使用TBitmap的ReleaseHandle,而不仅仅是Handle

如果您希望它与左上角对齐,而不是像资源管理器那样与右下角对齐,请使用LVBKIF_SOURCE_HBITMAP代替LVBKIF_TYPE_WATERMARK作为ulFlags值。

uses
  CommCtrl, ...;

type
  TListView = class(ComCtrls.TListView)
  protected
    procedure WndProc(var Message: TMessage);
      override;
  end;

  TForm4 = class(TForm)
    ListView1: TListView;
    procedure FormCreate(Sender: TObject);
  end;

procedure TListView.WndProc(var Message: TMessage);
begin
  if Message.Msg = WM_ERASEBKGND then
    DefaultHandler(Message)
  else
    inherited WndProc(Message);
end;

procedure TForm4.FormCreate(Sender: TObject);
var
  Img: TImage;
  BkImg: TLVBKImage;
begin
  FillChar(BkImg, SizeOf(BkImg), 0);
  BkImg.ulFlags := LVBKIF_TYPE_WATERMARK;
  // Load image and take ownership of the bitmap handle
  Img := TImage.Create(nil);
  try
    Img.Picture.LoadFromFile('C:\Watermark.bmp');
    BkImg.hbm := Img.Picture.Bitmap.ReleaseHandle;
  finally
    Img.Free;
  end;
  // Set the watermark
  SendMessage(ListView1.Handle, LVM_SETBKIMAGE, 0, LPARAM(@BkImg));
end;

拉伸水印

listview本身不支持在整个背景中拉伸位图。为此,您需要自己做一个StretchBlt以响应WM_ERASEBKGND。

type
  TMyListView = class(TListView)
  protected
    procedure CreateHandle; override;
    procedure CreateParams(var Params: TCreateParams); override;
    procedure WMEraseBkgnd(var Msg: TWMEraseBkgnd); message WM_ERASEBKGND;
  public
    Watermark: TBitmap;
  end;

procedure TMyListView.CreateHandle;
begin
  inherited;
  // Set text background color to transparent
  SendMessage(Handle, LVM_SETTEXTBKCOLOR, 0, CLR_NONE);
end;

procedure TMyListView.CreateParams(var Params: TCreateParams);
begin
  inherited;
  // Invalidate every time the listview is resized
  Params.Style := Params.Style or CS_HREDRAW or CS_VREDRAW;
end;

procedure TMyListView.WMEraseBkgnd(var Msg: TWMEraseBkgnd);
begin
  StretchBlt(Msg.DC, 0, 0, Width, Height, Watermark.Canvas.Handle,
    0, 0, Watermark.Width, Watermark.Height, SrcCopy);
  Msg.Result := 1;
end;

答案 1 :(得分:1)

Tlistview很不错,但如果你想要更多。我建议您必须更新VirtualStringTree(VirtualTreeView)非常灵活,您可以自定义几乎任何您想要的东西,而且最重要的是它是免费的。