CTreeCtrl显示系统文件图标

文章来源:http://www.diybl.com/course/3_program/c++/cppsl/200855/113035.html

最近写了一个获取系统文件图标的类CFileIcon,可以用在树控件中显示任意文件图标。
    类里面只有两个静态函数:

CImageList* CFileIcon::GetSysImgList()
{
//获取系统图标列表
    SHFILEINFO   shFinfo;  
    HIMAGELIST   hImgList
=NULL;  
   
    hImgList  
=   (HIMAGELIST)SHGetFileInfo("C:\\",  
       
0,  
       
&shFinfo,  
       
sizeof(shFinfo),  
        SHGFI_SYSICONINDEX  
|    
        SHGFI_SMALLICON );  
   
if(!hImgList)  
    {  
        AfxMessageBox(
"无法获取系统图标列表!");
       
return  NULL;  
    }     
   
   
return CImageList::FromHandle(hImgList);
}

int CFileIcon::GetSysIcon(const CString&fileName)
{
//获取文件图标函数
    CString str=fileName;
   
int iIcon=0;
   
bool bFileCreated=false;

   
//没提供全名时创建一个文件
    if(-1== str.FindOneOf("\\"))
    {
        str.Format(
"c:\\aa%s",CFileTool::GetExtName((constchar*)fileName).c_str());
        CFileTool::NewFile(str);
        bFileCreated
=true;
    }

   
//获取文件信息
    SHFILEINFO shFi;
   
if(!SHGetFileInfo(str,0,&shFi,sizeof(shFi),SHGFI_ICON|SHGFI_SMALLICON|SHGFI_DISPLAYNAME))
    {
       
return iIcon;
    }
    iIcon
=shFi.iIcon;
    DestroyIcon(shFi.hIcon);



   
//删除文件
    if(bFileCreated)
    {
        CFileTool::DelFile(str);
    }

   
return iIcon;
}

       其中用到的文件工具类代码如下:



string CFileTool::GetExtName( const string fileName)
{
// 获取文件扩展名
    string result = "" ;
   
int pos = fileName.find_last_of( '' . '' );
   
if (pos != - 1 )
    {
       
        result
= fileName.substr(pos,fileName.length() - pos);
    }

   
return result;
}

string CFileTool::GetShortName( const string fileName)
{
// 获取短文件名
    string result = fileName;
   
int pos = fileName.find_last_of( '' \\ '''' );
    if (pos != - 1 )
    {
        result
= fileName.substr(pos + 1 ,fileName.length() - pos - 1 );
    }

   
return result;
}

void CFileTool::NewFile( const char * fileName)
{
// 新建文件
    FILE * file;
    file
= fopen(fileName, " w " );
   
if (file != NULL)
    {
        fclose(file);
    }
}

void CFileTool::DelFile( const char * fileName)
{
// 删除文件
    remove(fileName);
}

       使用方法如下:
        1. 在对话框中创建一个CTreeCtrl 树控件 m_tree
        2. 在对话框初始化函数 OnInitDialog() 中为树控件设置系统图标列表



    m_tree.SetImageList(CFileIcon::GetSysImgList(), TVSIL_NORMAL);

        3. 往树控件中添加项



    CString fileName = " filelist.txt " ;    // 任意一个文件名 就一个 .txt 也行 :)
    int iIcon = CFileIcon::GetSysIcon(fileName); // 获取文件图标
    m_tree.InsertItem(fileName,iIcon,iIcon);

       运行效果如图:


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值