unit TreeNodeCustomSort;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Forms, Dialogs,
  Menus, Controls, StdCtrls, ComCtrls;

type
  TForm1 = class(TForm)
    TreeView1: TTreeView;
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

// BeginExample: TreeNodeCustomSort
// Method: ComCtrls.TTreeNode.CustomSort

// BeginCode
{
This example shows how to use the CustomSort method to order
a subtree in case-insensitive alphabetical order (either
forward or backward). The callback function CompareFunc
below calls the global AnsiStrIComp function to perform the
actual comparison.  This example requires two buttons and a
populated TreeView. Customsort only operates on the subtree
of the selected node.
}
function CustomSortProc(Node1, Node2: TTreeNode; Data: Longint): Integer; stdcall;
var val: Integer;
begin
  if Data = 0 then
    val := AnsiStrIComp(Pchar(Node1.Text), PChar(Node2.Text))
  else
    val := -AnsiStrIComp(PChar(Node1.Text), PChar(Node2.Text));
  Exit(val);
end;

{
This procedure can then be used as a parameter to CustomSort
to sort the children of a node:
}

procedure TForm1.Button1Click(Sender: TObject);
var node: TTreeNode;
begin
  node := TreeView1.Selected;
  node.CustomSort(@CustomSortProc, 0);  { Sorts in ascending order }
end;

procedure TForm1.Button2Click(Sender: TObject);
var node: TTreeNode;
begin
  node := TreeView1.Selected;
  node.CustomSort(@CustomSortProc, 1);  { Sorts in descending order }
end;
// EndCode
// EndExample: TreeNodeCustomSort
end.

