简述
在Windows系统中,根据扩展名来区分文件类型,比如:.txt(文本文件)、.exe(可执行程序)、*.zip(压缩文件),下面,我们来根据扩展名来获取对应的文件图标、类型。
源码
如下,我们根据扩展名来获取对应的文件图标、类型。
#include <windows.h>
#include <iostream>
// 获取文件图标
HICON fileIcon(std::string extention)
{
HICON icon = NULL;
if (extention.length() > 0)
{
LPCSTR name = extention.c_str();
SHFILEINFOA info;
if (SHGetFileInfoA(name,
FILE_ATTRIBUTE_NORMAL,
&info,
sizeof(info),
SHGFI_SYSICONINDEX | SHGFI_ICON | SHGFI_USEFILEATTRIBUTES))
{
icon = info.hIcon;
}
}
return icon;
}
// 获取文件类型
std::string fileType(std::string extention)
{
std::string type = "";
if (extention.length() > 0)
{
LPCSTR name = extention.c_str();
SHFILEINFOA info;
if (SHGetFileInfoA(name,
FILE_ATTRIBUTE_NORMAL,
&info,
sizeof(info),
SHGFI_TYPENAME | SHGFI_USEFILEATTRIBUTES))
{
type = info.szTypeName;
}
}
return type;
}
// 获取文件夹图标
HICON folderIcon()
{
std::string str = "folder";
LPCSTR name = str.c_str();
HICON icon = NULL;
SHFILEINFOA info;
if (SHGetFileInfoA(name,
FILE_ATTRIBUTE_DIRECTORY,
&info,
sizeof(info),
SHGFI_SYSICONINDEX | SHGFI_ICON | SHGFI_USEFILEATTRIBUTES))
{
icon = info.hIcon;
}
return icon;
}
// 获取文件夹类型
std::string folderType()
{
std::string str = "folder";
LPCSTR name = str.c_str();
std::string type;
SHFILEINFOA info;
if (SHGetFileInfoA(name,
FILE_ATTRIBUTE_DIRECTORY,
&info,
sizeof(info),
SHGFI_TYPENAME | SHGFI_USEFILEATTRIBUTES))
{
type = info.szTypeName;
}
return type;
}