首先是头文件,内容如下:
#include <tchar.h> #include "..\CommonFiles\CmnHdr.h" #include <Windows.h> #include <WindowsX.h> #include <CommCtrl.h> #include "resource.h" #pragma comment (lib,"comctl32.lib") BOOL InitTreeViewImageLists(HWND hwndTV); //该函数主要用于向TreeView控件中添加图片 HTREEITEM InitTreeCtrl(HWND hwnd,PTSTR pszCaption,int nLevel);//该函数向TreeView控件中添加内容
以下是实现函数:
#include "InitCtrls.h" extern HINSTANCE g_hInst; extern int g_nOpen; extern int g_nClose; BOOL InitTreeViewImageLists(HWND hwndTV){ HIMAGELIST himl; HBITMAP hBitmap; HICON hIcon; if((himl = ImageList_Create(16,16,FALSE,ILC_COLOR,0))==NULL) return FALSE; hBitmap = LoadBitmap(g_hInst,MAKEINTRESOURCE(IDB_BITMAP1)); hIcon = LoadIcon(g_hInst,MAKEINTRESOURCE(IDI_ICON1)); //g_nOpen = ImageList_Add(himl,hBitmap,(HBITMAP)NULL); //开始我用的是上面的方法,但不知道为什么添加不上,返回值-1 g_nOpen = ImageList_AddIcon(himl,hIcon); DeleteObject(hIcon); hBitmap = LoadBitmap(g_hInst,MAKEINTRESOURCE(IDB_BITMAP2)); hIcon = LoadIcon(g_hInst,MAKEINTRESOURCE(IDI_ICON2)); g_nClose = ImageList_AddIcon(himl,hIcon); DeleteObject(hIcon); if(ImageList_GetImageCount(himl) < 2) return FALSE; TreeView_SetImageList(GetDlgItem(GetParent(hwndTV),IDC_TREE),himl,TVSIL_NORMAL); return TRUE; } HTREEITEM InitTreeCtrl(HWND hwnd,PTSTR pszCaption,int nLevel){ HWND hwndTreeCtrl = GetDlgItem(hwnd,IDC_TREE); TVITEM tvi; TVINSERTSTRUCT tvins; static HTREEITEM hPrev = (HTREEITEM)TVI_FIRST;//hPrev 代表当前加入的新项 static HTREEITEM hPrevRootItem = NULL; //前一级目录 static HTREEITEM hPrevLev2Item = NULL; HTREEITEM hti ; tvi.mask = TVIF_TEXT|TVIF_IMAGE|TVIF_SELECTEDIMAGE|TVIF_PARAM; tvi.pszText = pszCaption; tvi.cchTextMax = sizeof(pszCaption)/sizeof(pszCaption[0]); tvins.item = tvi; tvins.hInsertAfter = hPrev; if(nLevel == 1) tvins.hParent = TVI_ROOT; else if(nLevel == 2) tvins.hParent = hPrevRootItem; else tvins.hParent = hPrevLev2Item; hPrev = TreeView_InsertItem(hwndTreeCtrl,&tvins); if(nLevel == 1) hPrevRootItem = hPrev; else hPrevLev2Item = hPrev; if(nLevel > 1){ hti = TreeView_GetParent(hwndTreeCtrl,hPrev); tvi.mask = TVIF_IMAGE | TVIF_SELECTEDIMAGE; tvi.hItem = hti; tvi.iImage = g_nOpen; tvi.iSelectedImage = g_nOpen; TreeView_SetItem(hwndTreeCtrl,&tvi); } return hPrev; }
时间: 2024-10-09 07:55:47