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

Use*_*ser 1 delphi tlistview delphi-xe

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

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

Zoë*_*son 9

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

如果你想让它对齐到左上角,而不是像资源管理器的右下方,使用LVBKIF_SOURCE_HBITMAP代替LVBKIF_TYPE_WATERMARKulFlags价值.

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;
Run Code Online (Sandbox Code Playgroud)

拉伸水印

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;
Run Code Online (Sandbox Code Playgroud)