Ejemplo n.º 1
0
 public static extern IntPtr SHGetFileInfo(
     string pszPath,
     uint dwFileAttributes,
     out ShellFileInfo psfi,
     uint cbFileInfo,
     uint uFlags);
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the directory or device icon.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns></returns>
        private static byte[] GetGenericIcon(string path, bool isDirectoryOrDevice)
        {
            const uint SHGFI_ICON = 0x000000100;
            const uint SHGFI_USEFILEATTRIBUTES = 0x000000010;
            const uint SHGFI_OPENICON = 0x000000002;
            const uint SHGFI_LARGEICON = 0x000000000;

            const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;

            // Get the folder icon
            byte[] icon = null;
            var shFileInfo = new ShellFileInfo();

            unsafe
            {
                try
                {
                    var flags = SHGFI_ICON | SHGFI_LARGEICON;

                    if (isDirectoryOrDevice)
                    {
                        flags = flags | SHGFI_USEFILEATTRIBUTES | SHGFI_OPENICON;
                    }

                    var result = SHGetFileInfo(
                        path,
                        FILE_ATTRIBUTE_DIRECTORY,
                        out shFileInfo,
                        (uint)Marshal.SizeOf(shFileInfo),
                        flags);

                    if (result == IntPtr.Zero)
                    {
                        throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
                    }

                    // Load the icon from an HICON handle
                    Icon.FromHandle(shFileInfo.hIcon);

                    icon = Icon.FromHandle(shFileInfo.hIcon).ToByteArray();
                }
                finally
                {
                    // Clean up, since this is unmanaged code
                    DestroyIcon(shFileInfo.hIcon);
                }
            }

            return icon;
        }