那就是使用SHGetFileInfo函数,调用这个函数可以获得所有关于文件的信息。它有一个聪明的选项,SHGFI_USEFILEATTRIBUTES,这个选项允许你传递一个假文件名,如mumble.txt。即便文件不存在,SHGetFileInfo也能获得你要的信息。
SHFILEINFO shfi;
memset(&shfi,0,sizeof(shfi));
SHGetFileInfo("foo.bmp",
FILE_ATTRIBUTE_NORMAL,
&shfi, sizeof(shfi),
SHGFI_ICON|SHGFI_USEFILEATTRIBUTES);
需要注意的一点是:
If SHGetFileInfo returns an icon handle in the hIcon member of the SHFILEINFO structure pointed to by psfi, you are responsible for freeing it with DestroyIcon when you no longer need it.
例子:
//CEdit m_ext;
//CStatic m_Icon;
LRESULT OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
// TODO: Add validation code
CString strExt;
char temp[256] = {0};
::GetWindowText(m_ext,temp,256);
strExt = temp;
strExt.TrimLeft(".");
CString strTemp = "nothing.";
strTemp += strExt;
SHFILEINFO shfi;
memset(&shfi,0,sizeof(shfi));
SHGetFileInfo(strTemp,
FILE_ATTRIBUTE_NORMAL,
&shfi,
sizeof(shfi),
SHGFI_ICON|SHGFI_USEFILEATTRIBUTES);
DestroyIcon(m_Icon.SetIcon(shfi.hIcon));
return 0;
}