|
Retrieving File System
Icons
Someone asked how I was getting the icons at runtime for drives, folders and files in FolderSizeBrowser. It's simply a call to SHGetFileInfo. The code is below. using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace FolderSizeBrowser
{
[StructLayout(LayoutKind.Sequential)]
public struct SHFILEINFO
{
public IntPtr hIcon;
public int iIcon;
public int dwAttributes;
public string szDisplayName;
public string szTypeName;
}
public enum IconSize
{
Large,
Small
}
public class IconStuff
{
private const uint SHGFI_SYSICONINDEX = 0x4000;
private const uint SHGFI_ICON = 0x100;
private const uint SHGFI_LARGEICON = 0x0;
private const uint SHGFI_SMALLICON = 0x1;
[DllImport("Shell32.dll")]
public static extern int SHGetFileInfo(string path, uint fileAttributes, out SHFILEINFO psfi, uint fileInfo, uint flags);
public static Icon GetIcon(string path, IconSize iconSize)
{
SHFILEINFO info = new SHFILEINFO();
uint size = iconSize == IconSize.Large ? SHGFI_LARGEICON : SHGFI_SMALLICON;
uint flags = SHGFI_SYSICONINDEX | size | SHGFI_ICON;
int hTcdf = SHGetFileInfo (path, 0, out info, (uint)Marshal.SizeOf(typeof(SHFILEINFO)), flags);
IntPtr handleIcon = info.hIcon;
Icon ico = Icon.FromHandle(handleIcon);
return ico;
}
}
}
|