title: Need Working Example of Shell32's ExtractAssociatedIcon Function in .NET
body: <p>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.</p>
  
  <pre><code>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, _
          &lt;MarshalAs(UnmanagedType.LPStr)&gt; ByVal lpIconPath As System.Text.StringBuilder, _
          ByRef lpiIcon As Integer) As IntPtr
  
      'Public Declare Auto Function ExtractAssociatedIcon Lib "shell32" ( _
      '    ByVal hInst As IntPtr, _
      '    &lt;MarshalAs(UnmanagedType.LPStr)&gt; ByVal lpIconPath As String, _
      '    ByRef lpiIcon As Integer) As IntPtr
  
      Friend Declare Auto Function DestroyIcon Lib "user32" (&lt;[In]()&gt; ByVal hIcon As IntPtr) As &lt;MarshalAs(UnmanagedType.Bool)&gt; 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
  </code></pre>
  
  <h3>Corrected</h3>
  
  <p><code>&lt;MarshalAs(UnmanagedType.LPStr)&gt;</code> was the problem. It should have been <code>LPTStr</code>, not <code>LPStr</code>.</p>