这个类的主要内容是从「微软帮助和支持」中找到的,经过测试可行。
说明:
- 作用是获取传入文件的图标;
- 传入参数要求是包括路径的文件名;
- 返回的是图标类型,经过测试,这个Icon是可以直接当Image来使用的;
代码:
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace csdemo.basic.Other
{
public class GetSystemIcon
{
public Icon Get(string fileName)
{
IntPtr hImgSmall;
SHFILEINFO shinfo = new SHFILEINFO();
hImgSmall = Win32.SHGetFileInfo(fileName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);
Icon fileIcon = Icon.FromHandle(shinfo.hIcon);
return fileIcon;
}
}
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public IntPtr iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
public string szTypeName;
};
class Win32
{
public const uint SHGFI_ICON = 0x100;
public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
public const uint SHGFI_SMALLICON = 0x1; // 'Small icon
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
}
}
参考:http://support.microsoft.com/kb/319350/zh-cn