public int AddShellIcon(string path, ShellIconType flags) { var info = new NativeMethods.SHFILEINFO(); try { var imageList = NativeMethods.SHGetFileInfo( path, 0, ref info, (uint)Marshal.SizeOf(info), ((uint)flags | NativeMethods.SHGFI_SMALLICON | NativeMethods.SHGFI_SYSICONINDEX) & ~NativeMethods.SHGFI_ICON ); if (imageList == IntPtr.Zero) return -1; if (imageList != _handle) throw new ArgumentException("Could not get image", "path"); return info.iIcon; } finally { if (info.hIcon != IntPtr.Zero) NativeMethods.DestroyIcon(info.hIcon); } }
public SystemImageList() { var fileInfo = new NativeMethods.SHFILEINFO(); _handle = NativeMethods.SHGetFileInfo( ".txt", 0, ref fileInfo, (uint)Marshal.SizeOf(fileInfo), NativeMethods.SHGFI_USEFILEATTRIBUTES | NativeMethods.SHGFI_SYSICONINDEX | NativeMethods.SHGFI_SMALLICON ); Debug.Assert(_handle != IntPtr.Zero); }
/// <summary> /// Gets the information for the specified /// file name and flags. /// </summary> public void GetInfo() { fileIcon = null; typeName = ""; displayName = ""; NativeMethods.SHFILEINFO shfi = new NativeMethods.SHFILEINFO(); uint shfiSize = (uint)Marshal.SizeOf(shfi.GetType()); IntPtr ret = NativeMethods.SHGetFileInfo( fileName, 0, ref shfi, shfiSize, (uint)(flags)); if (ret != IntPtr.Zero) { if (shfi.hIcon != IntPtr.Zero) { fileIcon = System.Drawing.Icon.FromHandle(shfi.hIcon); // Now owned by the GDI+ object //DestroyIcon(shfi.hIcon); } typeName = shfi.szTypeName; displayName = shfi.szDisplayName; } else { int err = NativeMethods.GetLastError(); Console.WriteLine("Error {0}", err); string txtS = new string('\0', 256); int len = NativeMethods.FormatMessage( NativeMethods.FORMAT_MESSAGE_FROM_SYSTEM | NativeMethods.FORMAT_MESSAGE_IGNORE_INSERTS, IntPtr.Zero, err, 0, txtS, 256, 0); Console.WriteLine("Len {0} text {1}", len, txtS); // throw exception } }