Create Treeview Controls
//=============================================================================
//COMMON CONTROLS: TREEVIEW - Copyright © 2000,2005 Ken Fitlike
//=============================================================================
//API functions used: CreateWindowEx,DefWindowProc,DestroyIcon,DispatchMessage,
//FreeLibrary,GetMessage,GetSystemMetrics,GetWindowLongPtr,ImageList_AddIcon,
//ImageList_Create,ImageList_Destroy,InitCommonControlsEx,LoadImage,
//LoadLibrary,lstrlen,MessageBox,MoveWindow,PostQuitMessage,RegisterClassEx,
//SendMessage,SetWindowLongPtr,ShowWindow,UpdateWindow,TranslateMessage,
//TreeView_SetImageList,WinMain.
//=============================================================================
//This demonstrates the creation of a treeview common control.
//
//BCC55 - Link with comctl32.lib
//MINGW - Link with libcomctl32.a (-lcomctl32)
//MSVC  - Link with comctl32.lib
//=============================================================================
#include <windows.h>  //include all the basics
#include <tchar.h>    //string and other mapping macros

#if defined __MINGW_H
#define _WIN32_IE 0x0400
#endif
#include <commctrl.h>

#include <string>
#include <vector>

//define an unicode string type alias
typedef std::basic_string<TCHAR> ustring;
//=============================================================================
//message processing function declarations
LRESULT CALLBACK WndProc(HWND,UINT,WPARAM,LPARAM);
int OnCreate(const HWND,CREATESTRUCT*);
void OnDestroy(const HWND);
void OnSize(const HWND,int,int,UINT);

//non-message function declarations
HWND CreateTreeview(const HWND,const HINSTANCE,DWORD,const RECT&,const int);
inline int ErrMsg(const ustring&);  
HTREEITEM InsertTreeviewItem(const HWND,const ustring& txt,
                             HTREEITEM htiParent);
bool SetTreeviewImagelist(const HWND);                             
void StartCommonControls(DWORD);

//setup some control id's
enum {
  IDC_TREEVIEW=200
};
//=============================================================================
int WINAPI WinMain(HINSTANCE hInst,HINSTANCE,LPSTR pStr,int nCmd)
{
ustring classname=_T("SIMPLEWND");
WNDCLASSEX wcx={0};  //used for storing information about the wnd 'class'

wcx.cbSize         = sizeof(WNDCLASSEX);           
wcx.lpfnWndProc    = WndProc;             //wnd Procedure pointer
wcx.hInstance      = hInst;               //app instance
//use 'LoadImage' to load wnd class icon and cursor as it supersedes the 
//obsolete functions 'LoadIcon' and 'LoadCursor', although these functions will 
//still work. Because the icon and cursor are loaded from system resources ie 
//they are shared, it is not necessary to free the image resources with either 
//'DestroyIcon' or 'DestroyCursor'.
wcx.hIcon         = reinterpret_cast<HICON>(LoadImage(0,IDI_APPLICATION,
                                            IMAGE_ICON,0,0,LR_SHARED));
wcx.hCursor       = reinterpret_cast<HCURSOR>(LoadImage(0,IDC_ARROW,
                                              IMAGE_CURSOR,0,0,LR_SHARED));
wcx.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BTNFACE+1);   
wcx.lpszClassName = classname.c_str(); 
//the window 'class' (not c++ class) has to be registered with the system
//before windows of that 'class' can be created
if (!RegisterClassEx(&wcx))
  {
  ErrMsg(_T("Failed to register wnd class"));
  return -1;
  }

int desktopwidth=GetSystemMetrics(SM_CXSCREEN);
int desktopheight=GetSystemMetrics(SM_CYSCREEN);

HWND hwnd=CreateWindowEx(0,                     //extended styles
                         classname.c_str(),     //name: wnd 'class'
                         _T("Common Controls - Treeview"), //wnd title
                         WS_OVERLAPPEDWINDOW,   //wnd style
                         desktopwidth/4,        //position:left
                         desktopheight/4,       //position: top
                         desktopwidth/2,        //width
                         desktopheight/2,       //height
                         0,                     //parent wnd handle
                         0,                     //menu handle/wnd id
                         hInst,                 //app instance
                         0);                    //user defined info
if (!hwnd)
  {
  ErrMsg(_T("Failed to create wnd"));
  return -1;
  }

ShowWindow(hwnd,nCmd); 
UpdateWindow(hwnd);
//start message loop - windows applications are 'event driven' waiting on user,
//application or system signals to determine what action, if any, to take. Note 
//that an error may cause GetMessage to return a negative value so, ideally,  
//this result should be tested for and appropriate action taken to deal with 
//it(the approach taken here is to simply quit the application).
MSG msg;
while (GetMessage(&msg,0,0,0)>0)
  {
  TranslateMessage(&msg);
  DispatchMessage(&msg);
  }
return static_cast<int>(msg.wParam);
}
//=============================================================================
LRESULT CALLBACK WndProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
{
switch (uMsg)
  {
  case WM_CREATE:
    {
    return OnCreate(hwnd,reinterpret_cast<CREATESTRUCT*>(lParam));
    }
  case WM_DESTROY:
    {
    OnDestroy(hwnd);
    return 0;
    }
  case WM_SIZE:
    {
    OnSize(hwnd,LOWORD(lParam),HIWORD(lParam),static_cast<UINT>(wParam));
    return 0;
    }
  default:
    //let system deal with msg
    return DefWindowProc(hwnd,uMsg,wParam,lParam);  
  }
}
//=============================================================================
int OnCreate(const HWND hwnd,CREATESTRUCT *cs)
{
//handles the WM_CREATE message of the main, parent window; return -1 to fail
//window creation
RECT rc={0,0,0,0};  //set dimensions in parent window's WM_SIZE handler 
StartCommonControls(ICC_TREEVIEW_CLASSES); //ICC_WIN95_CLASSES can also be used


HWND hTreeview=CreateTreeview(hwnd,cs->hInstance,TVS_HASLINES|TVS_LINESATROOT|
                              TVS_HASBUTTONS,rc,IDC_TREEVIEW);
                              
//now store the header control handle as the user data associated with the
//parent window so that it can be retrieved for later use. This will emit a 
//C4244 warning if /wp64 is enabled with ms compilers under win32 due to how 
//SetWindowLongPtr is typedef'd for 32bit and 64bit compatibility. The warning
//in this context can be safely ignored. Despite this being identified as a 
//glitch under msvc.net 2003, it still exists in the later msvc express 2005. 
//A workaround would be to wrap the offending call in #pragma warning 
//directives, or to typedef the fn properly for 32/64 bit compatibility. 
//See http://msdn.microsoft.com/msdnmag/issues/01/08/bugslayer/
//for details.
SetWindowLongPtr(hwnd,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(hTreeview));

SetTreeviewImagelist(hTreeview);

//add some items to the the tree view common control
HTREEITEM hPrev=InsertTreeviewItem(hTreeview,_T("First"),TVI_ROOT);

//sub items of first item
hPrev=InsertTreeviewItem(hTreeview,_T("Level01"),hPrev);  
//sub item of 'level01' item
hPrev=InsertTreeviewItem(hTreeview,_T("Level02"),hPrev); 
//sub item of 'level02' item 
hPrev=InsertTreeviewItem(hTreeview,_T("Level03"),hPrev);  

//insert second item at same level (root) as first item
hPrev=InsertTreeviewItem(hTreeview,_T("Second"),TVI_ROOT);  

//insert third item at same level (root) as first item
hPrev=InsertTreeviewItem(hTreeview,_T("Third"),TVI_ROOT);

//insert fourth item at same level (root) as first item
hPrev=InsertTreeviewItem(hTreeview,_T("Fourth"),TVI_ROOT);

return 0;
}
//=============================================================================
void OnDestroy(const HWND hwnd)
{
//get the treeview control handle which has been previously stored in the user
//data associated with the parent window.
HWND hTreeview=reinterpret_cast<HWND>(static_cast<LONG_PTR>
                                     (GetWindowLongPtr(hwnd,GWLP_USERDATA)));

//and free resources used by the treeview's image list
HIMAGELIST hImages=reinterpret_cast<HIMAGELIST>(SendMessage(hTreeview,
                                                TVM_GETIMAGELIST,0,0));

ImageList_Destroy(hImages);

PostQuitMessage(0); //signal end of application
}
//=============================================================================
void OnSize(const HWND hwnd,int cx,int cy,UINT flags)
{
//get the treeview control handle which has been previously stored in the user
//data associated with the parent window.
HWND hTreeview=reinterpret_cast<HWND>(static_cast<LONG_PTR>
                                     (GetWindowLongPtr(hwnd,GWLP_USERDATA)));
                                     
//resize listview common control so that it fills client area of its parent wnd
MoveWindow(hTreeview,0,0,cx,cy,TRUE);
}
//=============================================================================
HWND CreateTreeview(const HWND hParent,const HINSTANCE hInst,DWORD dwStyle,
                    const RECT& rc,const int id)
{
dwStyle|=WS_CHILD|WS_VISIBLE;
return CreateWindowEx(0,                  //extended styles
                      WC_TREEVIEW,        //control 'class' name
                      0,                  //control caption
                      dwStyle,            //wnd style
                      rc.left,            //position: left
                      rc.top,             //position: top
                      rc.right,           //width
                      rc.bottom,          //height
                      hParent,            //parent window handle
                      //control's ID
                      reinterpret_cast<HMENU>(static_cast<INT_PTR>(id)),
                      hInst,              //instance
                      0);                 //user defined info
}
//=============================================================================
inline int ErrMsg(const ustring& s)
{
return MessageBox(0,s.c_str(),_T("ERROR"),MB_OK|MB_ICONEXCLAMATION);
}
//=============================================================================
void StartCommonControls(DWORD flags)
{
//load the common controls dll, specifying the type of control(s) required 
INITCOMMONCONTROLSEX iccx;
iccx.dwSize=sizeof(INITCOMMONCONTROLSEX);
iccx.dwICC=flags;
InitCommonControlsEx(&iccx);
}
//=============================================================================
HTREEITEM InsertTreeviewItem(const HWND hTv,const ustring& txt,
                             HTREEITEM htiParent)
{
TVITEM tvi={0};

tvi.mask=TVIF_TEXT|TVIF_IMAGE|TVIF_SELECTEDIMAGE;


//copy the text into a temporary array (vector) so it's in a suitable form
//for the pszText member of the TVITEM struct to use. This avoids using
//const_cast on 'txt.c_str()' or variations applied directly to the string that
//break its constant nature.
std::vector<TCHAR> tmp(txt.begin(),txt.end());
tmp.push_back(_T('\0'));

tvi.pszText=&tmp[0];
tvi.cchTextMax=static_cast<int>(txt.length());  //length of item label
tvi.iImage=0;  //non-selected image index

TVINSERTSTRUCT tvis={0};

tvi.iSelectedImage=1;   //selected image index
tvis.item=tvi; 
tvis.hInsertAfter=0;
tvis.hParent=htiParent; //parent item of item to be inserted

return reinterpret_cast<HTREEITEM>(SendMessage(hTv,TVM_INSERTITEM,0,
                                   reinterpret_cast<LPARAM>(&tvis)));
}
//=============================================================================
bool SetTreeviewImagelist(const HWND hTv)
{
//set up and attach image lists to tree view common control
HIMAGELIST hImages=ImageList_Create(GetSystemMetrics(SM_CXSMICON),
                             GetSystemMetrics(SM_CYSMICON),
                             ILC_COLOR32|ILC_MASK,1,1);
if (hImages==0)
  {
  ErrMsg(_T("Failed to create image list."));
  return false;
  }
//get an instance handle for a source of icon images - for convenience use a
//known system dll
HINSTANCE hLib=LoadLibrary(_T("shell32.dll"));

if (!hLib)
  {
  ErrMsg(_T("Failed to load image resource library."));
  return false;
  }
  
int i;
for (i=4;i<6;++i)
  {
  //Because the icons are loaded from system resources  ie they are shared, 
  //it is not necessary to free the image resources with 'DestroyIcon'.
  HICON hIcon=reinterpret_cast<HICON>(LoadImage(hLib,
                               MAKEINTRESOURCE(i),
                               IMAGE_ICON,
                               0,0,
                               LR_SHARED));
  ImageList_AddIcon(hImages,hIcon); 
  }
FreeLibrary(hLib);  //done with the lib

//attach image lists to tree view common control
TreeView_SetImageList(hTv,hImages,TVSIL_NORMAL);

return true;
}
//=============================================================================