分类: C/C++
2008-04-23 21:42:15
VC控件 TreeCtrl 与 ListCtrl 演示
作者:兰州大学现物系
这个例子类似于 Windows 的资源管理器,程序运行界面如图一所示:
图一
主要用到的类有:
CListCtrl,CTreeCtrl,CImageList,CFileFind 和函数SHGetFileInfo()
简述步骤如下:
1、增加 TreeCtrl 的
TVS_HASBUTTONS,TVS_HASLINES、TVS_LINESATROOT Style,代码如下:
DWORD dwStyle = GetWindowLong(m_tree.m_hWnd,GWL_STYLE); dwStyle |= TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT; SetWindowLong(m_tree.m_hWnd,GWL_STYLE,dwStyle);2、为TreeCtrl添加Root项:
m_hRoot = m_tree.InsertItem("我的电脑"); InsertItem()的函数原形为 HTREEITEM InsertItem( LPCTSTR lpszItem, HTREEITEM hParent = TVI_ROOT, HTREEITEM hInsertAfter = TVI_LAST );3、获取本地逻辑驱动器,并添加:
void CTreeViewDlg::GetLogicalDrives(HTREEITEM hParent) { size_t szAllDriveStrings = GetLogicalDriveStrings(0,NULL); char *pDriveStrings = new char[szAllDriveStrings sizeof(_T(""))]; GetLogicalDriveStrings(szAllDriveStrings,pDriveStrings); size_t szDriveString = strlen(pDriveStrings); while(szDriveString > 0) { m_tree.InsertItem(pDriveStrings,hParent); pDriveStrings = szDriveString 1; szDriveString = strlen(pDriveStrings); } }4、添加TVN_EXPANDED消息处理函数,当一项展开时,为其子项添加下一级目录:
void CTreeViewDlg::OnItemexpandedTree(NMHDR* pNMHDR, LRESULT* pResult) { NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; // TODO: Add your control notification handler code here TVITEM item = pNMTreeView->itemNew; if(item.hItem == m_hRoot) return; HTREEITEM hChild = m_tree.GetChildItem(item.hItem); while(hChild) { AddSubDir(hChild); hChild = m_tree.GetNextItem(hChild,TVGN_NEXT); } *pResult = 0; }AddSubDir函数功能添加子项,具体代码见示例。
void CTreeViewDlg::OnSelchangedTree(NMHDR* pNMHDR, LRESULT* pResult) { m_list.DeleteAllItems(); NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR; TVITEM item = pNMTreeView->itemNew; if(item.hItem == m_hRoot) return; CString str = GetFullPath(item.hItem); if(str.Right(1) != "\\") str = "\\"; str = "*.*"; CFileFind file; BOOL bContinue = file.FindFile(str); while(bContinue) { bContinue = file.FindNextFile(); if(!file.IsDirectory() && !file.IsDots()) { SHFILEINFO info; CString temp = str; int index = temp.Find("*.*"); temp.Delete(index,3); SHGetFileInfo(temp file.GetFileName(), 0, &info,sizeof(&info), SHGFI_DISPLAYNAME | SHGFI_ICON); int i = m_ImageList.Add(info.hIcon); m_list.InsertItem(i,info.szDisplayName,i); } } *pResult = 0; }这只是一个简单的例子,你可以在 ListCtrl 中添加鼠标双击消息的处理函数,用 Process 打开该选中的文件; 该示例在VC6,xp下编译通过。