Posted on 2013-03-01 14:01
盛勝 閱讀(1239)
評(píng)論(0) 編輯 收藏 引用
這個(gè)例子類(lèi)似于 Windows 的資源管理器,程序運(yùn)行界面如圖一所示:

圖一
主要用到的類(lèi)有:
CListCtrl,CTreeCtrl,CImageList,CFileFind 和函數(shù)SHGetFileInfo()
簡(jiǎn)述步驟如下:
1、增加 TreeCtrl 的 TVS_HASBUTTONS,TVS_HASLINES、TVS_LINESATROOT Style,代碼如下:
1.
DWORD
dwStyle = GetWindowLong(m_tree.m_hWnd,GWL_STYLE);
2.
dwStyle |= TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT;
3.
SetWindowLong(m_tree.m_hWnd,GWL_STYLE,dwStyle);
2、為T(mén)reeCtrl添加Root項(xiàng):
1.
m_hRoot = m_tree.InsertItem(
"我的電腦"
);
2.
InsertItem()的函數(shù)原形為
3.
HTREEITEM InsertItem(
LPCTSTR
lpszItem, HTREEITEM hParent = TVI_ROOT,
4.
HTREEITEM hInsertAfter = TVI_LAST );
3、獲取本地邏輯驅(qū)動(dòng)器,并添加:
01.
void
CTreeViewDlg::GetLogicalDrives(HTREEITEM hParent)
02.
{
03.
size_t
szAllDriveStrings = GetLogicalDriveStrings(0,NULL);
04.
char
*pDriveStrings =
new
char
[szAllDriveStrings +
sizeof
(_T(
""
))];
05.
GetLogicalDriveStrings(szAllDriveStrings,pDriveStrings);
06.
size_t
szDriveString =
strlen
(pDriveStrings);
07.
while
(szDriveString > 0)
08.
{
09.
m_tree.InsertItem(pDriveStrings,hParent);
10.
pDriveStrings += szDriveString + 1;
11.
szDriveString =
strlen
(pDriveStrings);
12.
}
13.
}
4、添加TVN_EXPANDED消息處理函數(shù),當(dāng)一項(xiàng)展開(kāi)時(shí),為其子項(xiàng)添加下一級(jí)目錄:
01.
void
CTreeViewDlg::OnItemexpandedTree(NMHDR* pNMHDR,
LRESULT
* pResult)
02.
{
03.
NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
04.
// TODO: Add your control notification handler code here
05.
TVITEM item = pNMTreeView->itemNew;
06.
if
(item.hItem == m_hRoot)
07.
return
;
08.
HTREEITEM hChild = m_tree.GetChildItem(item.hItem);
09.
while
(hChild)
10.
{
11.
AddSubDir(hChild);
12.
hChild = m_tree.GetNextItem(hChild,TVGN_NEXT);
13.
}
14.
*pResult = 0;
15.
}
AddSubDir函數(shù)功能添加子項(xiàng),具體代碼見(jiàn)示例。
5、添加TVN_SELCHANGED消息處理函數(shù),在這個(gè)函數(shù)里,用GetFullPath()取得選中項(xiàng)的絕 路徑(GetFullPath()具體代碼看示例),在ListCtrl中添加文件而非文件夾的圖標(biāo):
01.
void
CTreeViewDlg::OnSelchangedTree(NMHDR* pNMHDR,
LRESULT
* pResult)
02.
{
03.
m_list.DeleteAllItems();
04.
NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
05.
TVITEM item = pNMTreeView->itemNew;
06.
if
(item.hItem == m_hRoot)
07.
return
;
08.
CString str = GetFullPath(item.hItem);
09.
if
(str.Right(1) !=
"\\"
)
10.
str +=
"\\"
;
11.
str +=
"*.*"
;
12.
CFileFind file;
13.
BOOL
bContinue = file.FindFile(str);
14.
while
(bContinue)
15.
{
16.
bContinue = file.FindNextFile();
17.
if
(!file.IsDirectory() && !file.IsDots())
18.
{
19.
SHFILEINFO info;
20.
CString temp = str;
21.
int
index = temp.Find(
"*.*"
);
22.
temp.Delete(index,3);
23.
SHGetFileInfo(temp + file.GetFileName(),
24.
0,
25.
&info,
sizeof
(&info),
26.
SHGFI_DISPLAYNAME | SHGFI_ICON);
27.
int
i = m_ImageList.Add(info.hIcon);
28.
m_list.InsertItem(i,info.szDisplayName,i);
29.
}
30.
}
31.
*pResult = 0;
32.
}
這只是一個(gè)簡(jiǎn)單的例子,你可以在 ListCtrl 中添加鼠標(biāo)雙擊消息的處理函數(shù),用 Process 打開(kāi)該選中的文件; 該示例在VC6,xp下編譯通過(guò)。
VC初學(xué)者,如有不足之處,請(qǐng)來(lái)信指教(waysen01@st.lzu.edu.cn)。