I need a working example of the ExtractAssociatedIcon function in Shell32.dll. I cannot get it working and I am out of ideas. I need another set of eyes on the following code. When the form loads, its icon should be set to the Visual Studio icon, but all I get is the default system icon.
Imports System.Runtime.InteropServices
Public Class Form1
Public Function ExtractIcon(ByVal path As String, ByVal handle As IntPtr) As Icon
Dim oResult As Icon
Dim hIcon As IntPtr
Dim iIndex As Integer
Dim oPath As New System.Text.StringBuilder(260, 260)
oPath.Append(path)
hIcon = ExtractAssociatedIcon(handle, oPath, iIndex)
'hIcon = ExtractAssociatedIcon(handle, path, iIndex)
Dim oIcon As Icon = Icon.FromHandle(hIcon)
oResult = DirectCast(oIcon.Clone, Icon)
DestroyIcon(hIcon)
Return oResult
End Function
Public Declare Auto Function ExtractAssociatedIcon Lib "shell32" ( _
ByVal hInst As IntPtr, _
<MarshalAs(UnmanagedType.LPStr)> ByVal lpIconPath As System.Text.StringBuilder, _
ByRef lpiIcon As Integer) As IntPtr
'Public Declare Auto Function ExtractAssociatedIcon Lib "shell32" ( _
' ByVal hInst As IntPtr, _
' <MarshalAs(UnmanagedType.LPStr)> ByVal lpIconPath As String, _
' ByRef lpiIcon As Integer) As IntPtr
Friend Declare Auto Function DestroyIcon Lib "user32" (<[In]()> ByVal hIcon As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'ExtractAssociatedIcon uses ExtractAssociatedIcon that is in Shell32.dll.
'This works, so why doesn't mine? What am I missing?
'Me.Icon = System.Drawing.Icon.ExtractAssociatedIcon("C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe")
Me.Icon = ExtractIcon("C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe", Me.Handle)
End Sub
End Class
Corrected
<MarshalAs(UnmanagedType.LPStr)>
was the problem. It should have been LPTStr
, not LPStr
.