unit AddChildObjectFirst;

interface

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

type
  TForm1 = class(TForm)
    TreeView1: TTreeView;
    Button1: TButton;
    ImageList: TImageList;
    procedure Button1Click(Sender: TObject);
    procedure TreeView1CustomDrawItem(Sender: TCustomTreeView; Node: TTreeNode;
      State: TCustomDrawState; var DefaultDraw: Boolean);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

// BeginExample: AddChildObjectFirst
// Method: ComCtrls.TTreeNodes.AddChildObjectFirst
// Method: ComCtrls.TTreeNodes.BeginUpdate
// Method: ComCtrls.TTreeNodes.EndUpdate

// BeginCode
{
The following example adds a new item to the selected item’s
list of child items in the tree view control. The new item
is added first in the list of child items. The new item is
identified by the text ‘New Item’. The TBitmap object is
attached to the new item.
}
procedure TForm1.Button1Click(Sender: TObject);
var
  MyBitMap : TBitmap;
  node : TTreeNode;
begin
  MyBitMap := TBitmap.Create;
  MyBitMap.LoadFromFile('littleB.bmp');
  TreeView1.Items.BeginUpdate;
  node:= TreeView1.Items.AddChildObjectFirst(
    TreeView1.Selected, 'New Item', MyBitMap);
//  node.ImageIndex:= -1;
  TreeView1.Items.EndUpdate;
end;
// EndCode
// EndExample: AddChildObjectFirst

procedure TForm1.TreeView1CustomDrawItem(Sender: TCustomTreeView;
  Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean);
var
  Bitmap: TBitmap;      // temporary variable for the item’s bitmap/
  Offset: Integer;      // text offset width
  Rect: TRect;
begin
  if (Node.Data = nil) then exit;
  DefaultDraw := False;
  Bitmap := TBitmap.Create;
  Rect := Node.DisplayRect(True);
  with Sender.Canvas do  // draw on control canvas, not on the form
  begin
    FillRect(Rect);       // clear the rectangle
    Offset := 2;          // provide default offset
    Bitmap := TBitmap(Node.Data);  // get the bitmap
    if Bitmap <> nil then
    begin
      DefaultDraw := False;
      BrushCopy(
        Bounds(Rect.Left, Rect.Top, Bitmap.Width, Bitmap.Height),
        Bitmap,
        Bounds(0, 0, Bitmap.Width, Bitmap.Height),
        clRed);  // render bitmap
      Offset := Bitmap.width + 6;    // add six pixels between bitmap and text
      // If we can't find a bitmap, let the default draw the item.
      TextOut(Rect.Left + Offset, Rect.Top, Node.Text)  // display the text
    end;
  end;
end;

end.
