VC控件 TreeCtrl 与 ListCtrl 演示

分类: VC.NET   出处:iocblog整理  更新时间:2008-06-19   添加到收藏  
    这个例子类似于 windows 的资源管理器,程序运行界面如图一所示:
主要用到的类有:
clistctrl,ctreectrl,cimagelist,cfilefind 和函数shgetfileinfo()

简述步骤如下:
1、增加 treectrl 的 tvs_hasbuttons,tvs_haslines、tvs_linesatroot style,代码如下:
(来源www.iocblog.net)
  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下编译通过。
  vc初学者,如有不足之处,请来信指教(waysen01@st.lzu.edu.cn)。
Tag: TreeCtrl ,ListCtrl



文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。