Copy codeThe Code is as follows: using System;
Using System. Collections. Generic;
Using System. Text;
Namespace WindowsFormsApplication1
{
Using System;
Using System. Drawing;
Using System. Runtime. InteropServices;
Using Microsoft. Win32;
Using System. Reflection;
Using System. Collections. Generic;
Namespace BlackFox. Win32
{
Public static class Icons
{
# Region Custom exceptions class
Public class IconNotFoundException: Exception
{
Public IconNotFoundException (string fileName, int index)
: Base (string. Format ("Icon with Id = {0} wasn't found in file {1}", index, fileName ))
{
}
}
Public class UnableToExtractIconsException: Exception
{
Public UnableToExtractIconsException (string fileName, int firstIconIndex, int iconCount)
: Base (string. format ("Tryed to extract {2} icons starting from the one with id {1} from the \" {0} \ "file but failed", fileName, firstIconIndex, iconCount ))
{
}
}
# Endregion
# Region DllImports
/// <Summary>
/// Contains information about a file object.
/// </Summary>
Struct SHFILEINFO
{
/// <Summary>
/// Handle to the icon that represents the file. You are responsible
/// Destroying this handle with DestroyIcon when you no longer need it.
/// </Summary>
Public IntPtr hIcon;
/// <Summary>
/// Index of the icon image within the system image list.
/// </Summary>
Public IntPtr iIcon;
/// <Summary>
/// Array of values that indicates the attributes of the file object.
/// For information about these values, see the IShellFolder: GetAttributesOf
/// Method.
/// </Summary>
Public uint dwAttributes;
/// <Summary>
/// String that contains the name of the file as it appears in the Microsoft
/// Windows Shell, or the path and file name of the file that contains
/// Icon representing the file.
/// </Summary>
[Financialas (UnmanagedType. ByValTStr, SizeConst = 260)]
Public string szDisplayName;
/// <Summary>
/// String that describes the type of file.
/// </Summary>
[Financialas (UnmanagedType. ByValTStr, SizeConst = 80)]
Public string szTypeName;
};
[Flags]
Enum FileInfoFlags: int
{
/// <Summary>
/// Retrieve the handle to the icon that represents the file and the index
/// Of the icon within the system image list. The handle is copied to
/// HIcon member of the structure specified by psfi, and the index is copied
/// To the iIcon member.
/// </Summary>
SHGFI_ICON = 0x000000100,
/// <Summary>
/// Indicates that the function shocould not attempt to access the file
/// Specified by pszPath. Rather, it shocould act as if the file specified
/// PszPath exists with the file attributes passed in dwFileAttributes.
/// </Summary>
SHGFI_USEFILEATTRIBUTES = 0x000000010
}
/// <Summary>
/// Creates an array of handles to large or small icons extracted from
/// The specified executable file, dynamic-link library (DLL), or icon
/// File.
/// </Summary>
/// <Param name = "lpszFile">
/// Name of an executable file, DLL, or icon file from which icons will
/// Be extracted.
/// </Param>
/// <Param name = "nIconIndex">
/// <Para>
/// Specifies the zero-based index of the first icon to extract.
/// Example, if this value is zero, the function extracts the first
/// Icon in the specified file.
/// </Para>
/// <Para>
/// If this value is 1 and <paramref name = "phiconLarge"/> and
/// <Paramref name = "phiconSmall"/> are both NULL, the function returns
/// The total number of icons in the specified file. If the file is
/// Executable file or DLL, the return value is the number
/// RT_GROUP_ICON resources. If the file is an. ico file, the return
/// Value is 1.
/// </Para>
/// <Para>
/// Windows 95/98/Me, Windows NT 4.0 and later: If this value is
/// Negative number and either <paramref name = "phiconLarge"/> or
/// <Paramref name = "phiconSmall"/> is not NULL, the function begins
/// Extracting the icon whose resource identifier is equal to
/// Absolute value of <paramref name = "nIconIndex"/>. For example, use-3
/// To extract the icon whose resource identifier is 3.
/// </Para>
/// </Param>
/// <Param name = "phIconLarge">
/// An array of icon handles that has es handles to the large icons
/// Extracted from the file. If this parameter is NULL, no large icons
/// Are extracted from the file.
/// </Param>
/// <Param name = "phIconSmall">
/// An array of icon handles that includes ES handles to the small icons
/// Extracted from the file. If this parameter is NULL, no small icons
/// Are extracted from the file.
/// </Param>
/// <Param name = "nIcons">
/// Specifies the number of icons to extract from the file.
/// </Param>
/// <Returns>
/// If the <paramref name = "nIconIndex"/> parameter is-1,
/// <Paramref name = "phIconLarge"/> parameter is NULL, and
/// <Paramref name = "phiconSmall"/> parameter is NULL, then the return
/// Value is the number of icons contained in the specified file.
/// Otherwise, the return value is the number of icons successfully
/// Extracted from the file.
/// </Returns>
[DllImport ("Shell32", CharSet = CharSet. Auto)]
Extern static int ExtractIconEx (
[Financialas (UnmanagedType. LPTStr)]
String lpszFile,
Int nIconIndex,
IntPtr [] phIconLarge,
IntPtr [] phIconSmall,
Int nIcons );
[DllImport ("Shell32", CharSet = CharSet. Auto)]
Extern static IntPtr SHGetFileInfo (
String pszPath,
Int dwFileAttributes,
Out SHFILEINFO psfi,
Int cbFileInfo,
FileInfoFlags uFlags );
# Endregion
/// <Summary>
/// Two constants extracted from the FileInfoFlags, the only that are
/// Meaningfull for the user of this class.
/// </Summary>
Public enum SystemIconSize: int
{
Large = 0x000000000,
Small = 0x000000001
}
/// <Summary>
/// Get the number of icons in the specified file.
/// </Summary>
/// <Param name = "fileName"> Full path of the file to look for. </param>
/// <Returns> </returns>
Static int GetIconsCountInFile (string fileName)
{
Return ExtractIconEx (fileName,-1, null, null, 0 );
}
# Region ExtractIcon-like functions
Public static void ExtractEx (string fileName, List <Icon> largeIcons,
List <Icon> smallIcons, int firstIconIndex, int iconCount)
{
/*
* Memory allocations
*/
IntPtr [] smallIconsPtrs = null;
IntPtr [] largeIconsPtrs = null;
If (smallIcons! = Null)
{
SmallIconsPtrs = new IntPtr [iconCount];
}
If (largeIcons! = Null)
{
LargeIconsPtrs = new IntPtr [iconCount];
}
/*
* Call to native Win32 API
*/
Int apiResult = ExtractIconEx (fileName, firstIconIndex, largeIconsPtrs, smallIconsPtrs, iconCount );
If (apiResult! = IconCount)
{
Throw new UnableToExtractIconsException (fileName, firstIconIndex, iconCount );
}
/*
* Fill lists
*/
If (smallIcons! = Null)
{
SmallIcons. Clear ();
Foreach (IntPtr actualIconPtr in smallIconsPtrs)
{
SmallIcons. Add (Icon. FromHandle (actualIconPtr ));
}
}
If (largeIcons! = Null)
{
LargeIcons. Clear ();
Foreach (IntPtr actualIconPtr in largeIconsPtrs)
{
LargeIcons. Add (Icon. FromHandle (actualIconPtr ));
}
}
}
Public static List <Icon> ExtractEx (string fileName, SystemIconSize size,
Int firstIconIndex, int iconCount)
{
List <Icon> iconList = new List <Icon> ();
Switch (size)
{
Case SystemIconSize. Large:
ExtractEx (fileName, iconList, null, firstIconIndex, iconCount );
Break;
Case SystemIconSize. Small:
ExtractEx (fileName, null, iconList, firstIconIndex, iconCount );
Break;
Default:
Throw new ArgumentOutOfRangeException ("size ");
}
Return iconList;
}
Public static void Extract (string fileName, List <Icon> largeIcons, List <Icon> smallIcons)
{
Int iconCount = GetIconsCountInFile (fileName );
ExtractEx (fileName, largeIcons, smallIcons, 0, iconCount );
}
Public static List <Icon> Extract (string fileName, SystemIconSize size)
{
Int iconCount = GetIconsCountInFile (fileName );
Return ExtractEx (fileName, size, 0, iconCount );
}
Public static Icon ExtractOne (string fileName, int index, SystemIconSize size)
{
Try
{
List <Icon> iconList = ExtractEx (fileName, size, index, 1 );
Return iconList [0];
}
Catch (UnableToExtractIconsException)
{
Throw new IconNotFoundException (fileName, index );
}
}
Public static void ExtractOne (string fileName, int index,
Out Icon largeIcon, out Icon smallIcon)
{
List <Icon> smallIconList = new List <Icon> ();
List <Icon> largeIconList = new List <Icon> ();
Try
{
ExtractEx (fileName, largeIconList, smallIconList, index, 1 );
LargeIcon = largeIconList [0];
SmallIcon = smallIconList [0];
}
Catch (UnableToExtractIconsException)
{
Throw new IconNotFoundException (fileName, index );
}
}
# Endregion
// This will look throw the registry
// To find if the Extension have an icon.
Public static Icon IconFromExtension (string extension,
SystemIconSize size)
{
// Add the '.' to the extension if needed
If (extension [0]! = '.') Extension = '.' + extension;
// Opens the registry for the wanted key.
RegistryKey Root = Registry. ClassesRoot;
RegistryKey ExtensionKey = Root. OpenSubKey (extension );
ExtensionKey. GetValueNames ();
RegistryKey ApplicationKey =
Root. OpenSubKey (ExtensionKey. GetValue (""). ToString ());
// Gets the name of the file that have the icon.
String IconLocation =
ApplicationKey. OpenSubKey ("DefaultIcon"). GetValue (""). ToString ();
String [] IconPath = IconLocation. Split (',');
If (IconPath [1] = null) IconPath [1] = "0 ";
IntPtr [] Large = new IntPtr [1], Small = new IntPtr [1];
// Extracts the icon from the file.
ExtractIconEx (IconPath [0],
Convert. ToInt16 (IconPath [1]), Large, Small, 1 );
Return size = SystemIconSize. Large?
Icon. FromHandle (Large [0]): Icon. FromHandle (Small [0]);
}
Public static Icon IconFromExtensionShell (string extension, SystemIconSize size)
{
// Add '.' if nessesry
If (extension [0]! = '.') Extension = '.' + extension;
// Temp struct for getting file shell info
SHFILEINFO fileInfo = new SHFILEINFO ();
SHGetFileInfo (
Extension,
,
Out fileInfo,
Marshal. SizeOf (fileInfo ),
FileInfoFlags. SHGFI_ICON | FileInfoFlags. SHGFI_USEFILEATTRIBUTES | (FileInfoFlags) size );
Return Icon. FromHandle (fileInfo. hIcon );
}
Public static Icon IconFromResource (string resourceName)
{
Assembly assembly = Assembly. GetCallingAssembly ();
Return new Icon (assembly. GetManifestResourceStream (resourceName ));
}
/// <Summary>
/// Parse strings in registry who contains the name of the icon and
/// The index of the icon an return both parts.
/// </Summary>
/// <Param name = "regString"> The full string in the form "path, index" as found in registry. </param>
/// <Param name = "fileName"> The "path" part of the string. </param>
/// <Param name = "index"> The "index" part of the string. </param>
Public static void ExtractInformationsFromRegistryString (
String regString, out string fileName, out int index)
{
If (regString = null)
{
Throw new ArgumentNullException ("regString ");
}
If (regString. Length = 0)
{
Throw new ArgumentException ("The string shocould not be empty.", "regString ");
}
Index = 0;
String [] strArr = regString. Replace ("\" "," "). Split (',');
FileName = strArr [0]. Trim ();
If (strArr. Length> 1)
{
Int. TryParse (strArr [1]. Trim (), out index );
}
}
Public static Icon ExtractFromRegistryString (string regString, SystemIconSize size)
{
String fileName;
Int index;
ExtractInformationsFromRegistryString (regString, out fileName, out index );
Return ExtractOne (fileName, index, size );
}
}
}
}
Copy codeThe Code is as follows: // <summary>
/// Main entry point of the application.
/// </Summary>
[STAThread]
Static void Main ()
{
Application. EnableVisualStyles ();
Application. SetCompatibleTextRenderingDefault (false );
PictureBox pict = new PictureBox ();
Pict. Image = BlackFox. Win32.Icons. IconFromExtension (". zip", BlackFox. Win32.Icons. SystemIconSize. Large). ToBitmap ();
Pict. Dock = DockStyle. Fill;
Pict. SizeMode = PictureBoxSizeMode. CenterImage;
Form form = new Form ();
Form. Controls. Add (pict );
Application. Run (form );
}