VC控件 TreeCtrl 与 ListCtrl 演示(zz)
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);
![](http://www.vckbase.com/document/image/paragraph.gif)
m_hRoot = m_tree.InsertItem("我的电脑"); InsertItem()的函数原形为 HTREEITEM InsertItem( LPCTSTR lpszItem, HTREEITEM hParent = TVI_ROOT, HTREEITEM hInsertAfter = TVI_LAST );
![](http://www.vckbase.com/document/image/paragraph.gif)
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); } }
![](http://www.vckbase.com/document/image/paragraph.gif)
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函数功能添加子项,具体代码见示例。
![](http://www.vckbase.com/document/image/paragraph.gif)
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下编译通过。
VC初学者,如有不足之处,请来信指教(waysen01@st.lzu.edu.cn)。
原文地址:http://www.vckbase.com/document/viewdoc/?id=836