2010. május 31., hétfő

Display a sort order indicator in the column header of a TListView


Problem/Question/Abstract:

How can I display a sort order arrow on the tiltle row in TListView control (on the right side of the column caption)?

Answer:

The easiest way would be to add the arrow picture to the imagelist, assign it to the listview's smallimages property and specify the image index to the column (ImageIndex property of the TListColumn). Now you'll see the picture on the left side of the column header.

Another approach would be to draw the header by yourself. In case you're working with the standard (not overridden)TListView control, you can set the new window proc to the header in the form's OnCreate event. In the new header's window procedure you can check up if the WM_PAINT message is coming and perform custom drawing for the header or its part. See the example below for details:

{ ... }
type
  TForm1 = class(TForm)
    ListView1: TListView;
    { ... }
  protected
    FHeader: longint;
    FOldWndProc: pointer;
    procedure HeaderWndProc(var Message: TMessage);
  end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  FHeader := ListView_GetHeader(ListView1.Handle);
  FOldWndProc := Pointer(GetWindowLong(FHeader, GWL_WNDPROC));
  SetWindowLong(FHeader, GWL_WNDPROC,
    integer(Classes.MakeObjectInstance(HeaderWndProc)));
end;

procedure TForm1.HeaderWndProc(var Message: TMessage);
var
  XCanvas: TCanvas;
  XDC: HDC;
  XSizeRect: TRect;
begin
  if Assigned(FOldWndProc) then
    Message.Result := CallWindowProc(FOldWndProc, FHeader, Message.Msg,
      Message.WParam, Message.LParam);
  case Message.Msg of
    WM_PAINT:
      begin
        XCanvas := TCanvas.Create;
        XDC := GetWindowDC(FHeader);
        try
          XCanvas.Handle := XDC;
          Windows.GetClientRect(FHeader, XSizeRect);
          XCanvas.Brush.Color := clRed;
          XCanvas.FillRect(XSizeRect);
          {draw the new header's content here...}
        finally
          ReleaseDC(FHeader, XDC);
          XCanvas.Free;
        end;
      end;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése