
Imports System.Runtime.InteropServices

Public Enum IconSize
  Small
  Large
End Enum

Public Class IconExtractor

  '----------------------------------------------------------------------------
  '
  ' Description: Extracts the icon associated with any file on your system.
  ' Author: WidgetMan http://softwidgets.com
  '
  ' Remarks...
  '
  ' Class requires the IconSize enumeration that is implemented in this
  ' same file. For best results, draw an icon from within a control's Paint
  ' event via the e.Graphics.DrawIcon method.
  '
  '----------------------------------------------------------------------------

    Private Const SHGFI_ICON As Integer = &H100
    Private Const SHGFI_SMALLICON As Integer = &H1
    Private Const SHGFI_LARGEICON As Integer = &H0

  Private Structure SHFILEINFO

    Public hIcon As IntPtr
    Public iIcon As Integer
    Public dwAttributes As Integer

    <VBFixedString(260), MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)> _
    Public szDisplayName As String

    <VBFixedString(80), MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)> _
    Public szTypeName As String

  End Structure

  Private Declare Function SHGetFileInfo Lib "shell32" Alias "SHGetFileInfoA" _
   (ByVal pszPath As String, _
    ByVal dwFileAttributes As Integer, _
    ByRef psfi As SHFILEINFO, _
    ByVal ByValcbFileInfo As Integer, _
    ByVal uFlags As Integer) As Integer

  Public Sub New()
  End Sub

  Public Overloads Function Extract(ByVal File As String, ByVal Size As IconSize) As System.Drawing.Icon
        Dim aSHFileInfo As SHFILEINFO
        Dim cbFileInfo As Integer
        Dim uflags As Integer
        Dim Icon As System.Drawing.Icon

        Select Case Size
            Case IconSize.Large
                uflags = SHGFI_ICON Or SHGFI_LARGEICON
            Case Else
                uflags = SHGFI_ICON Or SHGFI_SMALLICON
        End Select

        cbFileInfo = Marshal.SizeOf(aSHFileInfo)

        SHGetFileInfo(File, 0, aSHFileInfo, cbFileInfo, uflags)

        Icon = System.Drawing.Icon.FromHandle(aSHFileInfo.hIcon)

        Return Icon
    End Function

  Public Overloads Function Extract(ByVal File As String) As System.Drawing.Icon
    Return Me.Extract(File, IconSize.Small)
  End Function

End Class