Working ChangeIconDialog in VB 2005 Express

JumpyNET

Centurion
Joined
Apr 4, 2005
Messages
196
This example let's you select an icon and draw the 16x16 and 32x32 icons to a picture box.

Just create a new form with two picture boxes and one button. Then use the following code:

Code:
Public Class Form1

    Private Declare Unicode Function SHChangeIconDialogW Lib "shell32" Alias "PickIconDlg" (ByVal hOwner As IntPtr, ByVal szFilename As String, ByVal Reserved As Integer, ByRef lpIconIndex As Integer) As Integer
    Private Declare Ansi Function SHChangeIconDialogA Lib "shell32" Alias "PickIconDlg" (ByVal hOwner As IntPtr, ByVal szFilename As String, ByVal Reserved As Integer, ByRef lpIconIndex As Integer) As Integer
    Private Declare Function ExtractIconEx Lib "shell32.dll" Alias "ExtractIconExA" (ByVal lpszFile As String, ByVal nIconIndex As Int32, ByRef phiconLarge As IntPtr, ByRef phiconSmall As IntPtr, ByVal nIcons As Int32) As Int32

    Dim IconName As String

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        BrowseForIcon()
    End Sub

    Private Sub BrowseForIcon()

        Dim FileName As String = "%SystemRoot%\system32\shell32.dll"
        Dim Index As Integer = 216
        Dim Retval As Integer

        'For some odd reason you must make the FileName string longer
        'than the path of the icon you will select with the dialog
        FileName = FileName & Chr(0) & Space(1000) & Chr(0)
        If System.Environment.OSVersion.Platform = PlatformID.Win32NT Then
            Retval = SHChangeIconDialogW(Me.Handle, FileName, Len(FileName) + 1, Index)
        Else
            Retval = SHChangeIconDialogA(Me.Handle, FileName, Len(FileName) + 1, Index)
        End If

        IconName = (Split(FileName, Chr(0))(0) & "," & Index)
        DrawAssociatedIcon()

    End Sub

    Private Sub DrawAssociatedIcon()

        Dim FileName As String
        Dim Index As Integer
        FileName = Split(IconName, ",")(0)
        Index = Split(IconName, ",")(1)

        Dim icoLarge As IntPtr
        Dim icoSmall As IntPtr
        ExtractIconEx(FileName, Index, icoLarge, icoSmall, 1)
        If Not icoLarge.Equals(IntPtr.Zero) Then
            Dim i As Icon = System.Drawing.Icon.FromHandle(icoLarge)
            PictureBox1.Image = i.ToBitmap
        End If
        If Not icoSmall.Equals(IntPtr.Zero) Then
            Dim i As Icon = System.Drawing.Icon.FromHandle(icoSmall)
            PictureBox2.Image = i.ToBitmap
        End If

    End Sub

End Class


PS: I had some trouble porting this to VB2005, so I decided to post it here to help others.
 
Back
Top