17 maggio 2006

VB.NET: Recuperare icone da un file

Utilizzando l'API SHGetFileInfo (contenuta nella shell32.dll) è possibile ricavare l'icona associata ad un qualsiasi file di windows, sia contenuta in esso, sia associata dal sistema operativo.
E' necessario l'utilizzo di pInvoke e la rimappatura della struttura SHFILEINFO.


Private Structure SHFILEINFO
     Public hIcon As IntPtr ' : icon
     Public iIcon As Integer ' : icondex
     Public dwAttributes As Integer ' : SFGAO_ flags
     <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)> _
     Public szDisplayName As String
     <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)> _
     Public szTypeName As String
End Structure



Public Const SHGFI_ICON = &H100 ' get icon
Public Const SHGFI_LARGEICON = &H0 ' get large icon
Public Const SHGFI_SMALLICON = &H1 ' get small icon



Private Declare Auto Function SHGetFileInfo Lib "shell32.dll" _
     (ByVal pszPath As String, _
     ByVal dwFileAttributes As Integer, _
     ByRef psfi As SHFILEINFO, _
     ByVal cbFileInfo As Integer, _
     ByVal uFlags As Integer) As IntPtr



Public Function ExtractIconFromFile(ByVal FileName As String, _
     Optional ByVal Type As Long = SHGFI_LARGEICON) As Icon
     Dim hImg As IntPtr
     Dim shinfo As SHFILEINFO
     shinfo = New SHFILEINFO
     hImg = SHGetFileInfo(FileName, 0, shinfo, _
     Marshal.SizeOf(shinfo), _
     SHGFI_ICON Or Type)
     Dim myIcon As System.Drawing.Icon
     If Not shinfo.hIcon.Equals(IntPtr.Zero) Then
          myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon)
     Else
          myIcon = Nothing
     End If
     Return myIcon
End Function



La funzione si può facilmente estendere per recuperare anche icone che non siano quelle con indice 0.


Nessun commento: