文章来源: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);
运行效果如图: