1. Computing & Technology

Discuss in my forum

Add Custom Sorting To Delphi's TShellListView Control

By , About.com Guide

One PopupMenu, one ShellListView and Custom Sorting ... Here We Go!
TShellListView Sorting Popup

TShellListView Sorting Popup

Once you have the TCustomShellListView tweaked by exposing the FFolders field as a read-only FolderList property, you can call the Sort method of the TList type providing it with your own custom sorting function to custom sort the elements (files and folders) displayed by the TShellListView control.

TShellListView Custom Sort - Test Project

Drop a TShellListView ("ShellListView1") on a form ("ShellListSortForm"). Add one TPopupMenu ("shellListSortPopup"). Add 4 menu items to the menu.

Before the popup is displayed we want the items of the popup to match column names as used by the shell list view control. Handle the "OnPopup" event as:

procedure TShellListSortForm.shellListSortPopupPopup(Sender: TObject);
var
  c: Integer;
begin
  //4 columns in "vsReport" view
  for c := 0 to ShellListView1.Columns.Count - 1 do
  begin
    shellListSortPopup.Items[c].Caption := ShellListView1.Columns[c].Caption;
    shellListSortPopup.Items[c].Tag := c;
  end;
end;

In the OnCreate event handler for the form, assign the OnClick procedure for popup menu items:

//form OnCreate
procedure TShellListSortForm.FormCreate(Sender: TObject);
var
  cnt: Integer;
begin
  ShellListView1.PopupMenu := shellListSortPopup;

  for cnt := 0 to shellListSortPopup.Items.Count - 1 do
    shellListSortPopup.Items[cnt].OnClick := shellListSortPopupItemClick;
end;
The shellListSortPopupItemClick is a declared as a private method of the form, implemented as:
procedure TShellListSortForm.shellListSortPopupItemClick(Sender: TObject);
begin
  if shellListSortColumn <> TMenuItem(Sender).Tag then
    shellListSortColumn := TMenuItem(Sender).Tag
  else
    shellListSortAscending := NOT shellListSortAscending;

  //the actual sort
  ShellListView1.FolderList.Sort(@ShellCompare);
  ShellListView1.Invalidate;
end;
The two variables "shellListSortColumn" and "shellListSortAscending" are declared at the unit level (in the impementation section) to hold the current sort column and sort direction
...
implementation

var
  shellListSortColumn : integer;
  shellListSortAscending : boolean;
Finally, the implementation of the actual sorting using the ShellCompare function is on the next page.

©2012 About.com. All rights reserved.

A part of The New York Times Company.