using System.Runtime.InteropServices;
2. use this function in main class
GetFileIcon(fileName, IconSize.Small,false);
public Icon GetFileIcon(string fileName, IconSize argSize, Boolean isDir)
{
try
{
IntPtr hImgSmall;
SHFILEINFO shInfo = new SHFILEINFO();
uint dwAttribs = 0;
uint uFlags = Win32.SHGFI_ICON;
if (argSize == IconSize.Small)
uFlags = uFlags | Win32.SHGFI_SMALLICON;
else
uFlags = uFlags | Win32.SHGFI_LARGEICON;
if (!Directory.Exists(fileName) && !File.Exists(fileName))
{
if (isDir)
dwAttribs = dwAttribs | Win32.FILE_ATTRIBUTE_DIRECTORY;
else
dwAttribs = dwAttribs | Win32.FILE_ATTRIBUTE_NORMAL;
uFlags = uFlags | Win32.SHGFI_USEFILEATTRIBUTES;
}
hImgSmall = Win32.SHGetFileInfo(fileName, dwAttribs, ref shInfo, Convert.ToUInt32(Marshal.SizeOf(shInfo)), uFlags);
return (Icon )Icon.FromHandle(shInfo.hIcon).Clone();
Win32.DestroyIcon(shInfo.hIcon);
}
catch (Exception ex)
{
return null;
}
}
3. use this code out of the main class
public enum IconSize
{
Small,
Large
}
[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;
}
public class Win32
{
public const uint FILE_ATTRIBUTE_NORMAL = 0x80;
public const uint FILE_ATTRIBUTE_DIRECTORY = 0x10;
public const uint SHGFI_ICON = 0x100 ; //' get icon
public const uint SHGFI_LARGEICON = 0x0 ; //' get large icon
public const uint SHGFI_SMALLICON = 0x1 ; //' get small icon
public const uint SHGFI_USEFILEATTRIBUTES = 0x10; //' use passed dwFileAttribute
public const uint SHGFI_TYPENAME = 0x400 ; //' get type name
[DllImport("shell32.dll", EntryPoint="SHGetFileInfo", CallingConvention=CallingConvention.StdCall)]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
[DllImport("User32.dll")]
public static extern int DestroyIcon(IntPtr hIcon);
}
沒有留言:
張貼留言