Jyina
Jyina

Reputation: 2892

System.ArgumentException: Win32 handle that was passed to Icon is not valid or is the wrong type

I have the below code to load an icon using Shell32 dll. It works fine on my machine. But one of the systems in production environment got an exception saying "System.ArgumentException: Win32 handle that was passed to Icon is not valid or is the wrong type". Any idea why we get this error? Thank you!

Public Function GetExecutableIcon() As Icon
    Dim large As IntPtr
    Dim small As IntPtr
    ExtractIconEx(Application.ExecutablePath, 0, large, small, 1)

    Return Icon.FromHandle(small)

End Function

<DllImport("Shell32")> _
Public Shared Function ExtractIconEx(ByVal sFile As String, ByVal iIndex As Integer, 
                 ByRef piLargeVersion As IntPtr, ByRef piSmallVersion As IntPtr, 
                 ByVal amountIcons As Integer) As Integer

End Function

Upvotes: 0

Views: 2477

Answers (2)

Try this:

<DllImport("Shell32")> _
Public Shared Function ExtractIconEx(ByVal sFile As String, ByVal iIndex As Integer, 
             ByRef piLargeVersion As IntPtr, ByRef piSmallVersion As IntPtr, 
             ByVal amountIcons As Integer) As Integer

Public Function GetExecutableIcon() As Icon
    Dim num As Integer = 10
    Dim large(num - 1) As IntPtr
    Dim small(num - 1) As IntPtr

    ExtractIconEx("C:\Windows\System32\Shell32.dll", 0, large(0), small(0), num)

    Return Icon.FromHandle(small(6)) 'change the index accordingly

End Function

Upvotes: 1

weloytty
weloytty

Reputation: 6098

Is your declaration correct? http://www.pinvoke.net/default.aspx/shell32.ExtractIconEx shows

<DllImport("shell32.dll", CharSet:=CharSet.Auto)> _
 Shared Function ExtractIconEx(ByVal szFileName As String, _
             ByVal nIconIndex As Integer, _
             ByVal phiconLarge() As IntPtr, _
             ByVal phiconSmall() As IntPtr, _
             ByVal nIcons As UInteger) As UInteger
 End Function

Upvotes: 1

Related Questions