//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "AddChildObjectFirst.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
// 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.
*/
#include <memory>       //for STL auto_ptr class
Graphics::TBitmap *MyBitMap;

void __fastcall TForm1::Button1Click(TObject *Sender)
{
  static std::auto_ptr<Graphics::TBitmap> _MyBitMapCleaner((MyBitMap = new Graphics::TBitmap()));  // just create it once
  MyBitMap->LoadFromFile("..\\littleB.bmp");
  TreeView1->Items->BeginUpdate(); // keep the node from painting until it's built
  TreeView1->Items->AddChildObjectFirst(
	TreeView1->Selected, "New Item", MyBitMap);
  TreeView1->Items->EndUpdate();
}
// EndCode
// EndExample: AddChildObjectFirst

void __fastcall TForm1::TreeView1CustomDrawItem(TCustomTreeView *Sender,
      TTreeNode *Node, TCustomDrawState State, bool &DefaultDraw)
{
  int Offset = 2;      // text offset width

  DefaultDraw = (Node->Data == NULL);  // If we can't find a bitmap,
  if (!DefaultDraw) 			       // let the default draw the item.
  {
	Graphics::TBitmap *bitmap = reinterpret_cast<Graphics::TBitmap *>(Node->Data);  // get the bitmap
	TRect NodeRect = Node->DisplayRect(True);
	// draw on control canvas, not on the form
	Sender->Canvas->FillRect(NodeRect);       // clear the rectangle
	TRect SrcRect = Bounds(0, 0, bitmap->Width, bitmap->Height);
	TRect DstRect = Bounds(NodeRect.Left, NodeRect.Top, bitmap->Width, bitmap->Height);
	TreeView1->Canvas->BrushCopy(
	  DstRect,
	  bitmap,
	  SrcRect,
	  clRed);  // render bitmap

	Offset = bitmap->Width + 6;    // add six pixels between bitmap and text
	Sender->Canvas->TextOut(NodeRect.Left + Offset, NodeRect.Top, Node->Text);  // display the text
  }
}
//---------------------------------------------------------------------------
