圖一
主要用到的類有:
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函數功能添加子項,具體代碼見示例。
5、添加TVN_SELCHANGED消息處理函數,在這個函數里,用GetFullPath()取得選中項的絕 路徑(GetFullPath()具體代碼看示例),在ListCtrl中添加文件而非文件夾的圖標: 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下編譯通過。