You can easily extend this code to work for all columns in a ListView; Declare two variables (in the private section of the form):
ColumnToSort: Integer; Climb: Boolean;
Initialize them in a FormCreate procedure using 0 and True.
procedure TForm1.ListView1ColumnClick(Sender: TObject; Column: ListColumn); var Header: HWND; Item: THDItem; begin Header := ListView_GetHeader(ListView1.Handle); ZeroMemory(@Item, SizeOf(Item)); Item.Mask := HDI_FORMAT; // Clear the previous arrow Header_GetItem(Header, ColumnToSort, Item); Item.fmt := Item.fmt and not (HDF_SORTUP or HDF_SORTDOWN);//remove both flags Header_SetItem(Header, ColumnToSort, Item); if Column.Index = ColumnToSort then Ascending := not Ascending else ColumnToSort := Column.Index; // Get the new column Header_GetItem(Header, ColumnToSort, Item); Item.fmt := Item.fmt and not (HDF_SORTUP or HDF_SORTDOWN);//remove both flags if Ascending then Item.fmt := Item.fmt or HDF_SORTUP//include the sort ascending flag else Item.fmt := Item.fmt or HDF_SORTDOWN;//include the sort descending flag Header_SetItem(Header, ColumnToSort, Item); with ListView1 do begin Items.BeginUpdate; AlphaSort; Items.EndUpdate; end; end;
Of course, you will need to provide your own OnCompare function to actually sort the columns. This code displays the sort arrow in the column header with a click.
source share