传递给 Icon 的 Win32 句柄无效或类型错误

Win32 handle that was passed to Icon is not valid or is the wrong type

我的代码存在以下问题。

Win32 handle that was passed to Icon is not valid or is the wrong type

代码行如下:

SHFILEINFO声明

Private Structure SHFILEINFO
    Public hIcon As IntPtr            ' : iconc
    Public iIcon As Integer           ' : icondex
    Public dwAttributes As Integer    ' : SFGAO_ flags
     _
    Public szDisplayName As String
     _
    Public szTypeName As String
End Structure

SHGetFileInfo 声明

Private Declare Auto Function SHGetFileInfo Lib "shell32.dll" _
        (ByVal pszPath As String, _
         ByVal dwFileAttributes As Integer, _
         ByRef psfi As SHFILEINFO, _
         ByVal cbFileInfo As Integer, _
         ByVal uFlags As Integer) As IntPtr

Private Const SHGFI_ICON = &H100
Private Const SHGFI_SMALLICON = &H1
Private Const SHGFI_LARGEICON = &H0    ' Large icon
Private Const MAX_PATH = 260

SHGetFileInfo 用法

Private Sub AddImageToImageListBox(ByVal strFileName As String)
    On Error GoTo errHandler

    Dim shInfo As SHFILEINFO
    shInfo = New SHFILEINFO()

    shInfo.szDisplayName = New String(vbNullChar, MAX_PATH)
    shInfo.szTypeName = New String(vbNullChar, 80)

    Dim hIcon As IntPtr
    hIcon = SHGetFileInfo(strFileName, 0, shInfo, Marshal.SizeOf(shInfo), SHGFI_ICON Or SHGFI_SMALLICON)

    Dim MyIcon As Drawing.Bitmap
    MyIcon = Drawing.Icon.FromHandle(shInfo.hIcon).ToBitmap
    imgAttachment.AddImage(MyIcon)
    ilstAttachments.Items.Add(strFileName.ToString(), imgAttachment.Images.Count - 1)

    Exit Sub
errHandler:
    ErrMsg("AddImageToImageListBox (errHandler)")
End Sub

运行时间

这是传递给 SHGetFileInfo 的值。

strFileName = "Copy (223) of Uncollected Card - Multiple Pages.TIF"
shInfo.dwAttributes = 0
shInfo.hIcon = 0
shInfo.iIcon = 0
shInfo.szDisplayName = ""
shInfo.szTypeName = ""

错误

当上述值被传递给 SHGetFileInfo 时,它 returns 0 值从而使 hIcon = 0。

当它达到

MyIcon = Drawing.Icon.FromHandle(shInfo.hIcon).ToBitmap

出现以下错误

Win32 handle that was passed to Icon is not valid or is the wrong type 

你们能帮我确定是什么问题吗?

谢谢

尝试将 SHFILEINFOSHGetFileInfo 更改为此

   Private Structure SHFILEINFO
        Public hIcon As IntPtr            ' : iconc
        Public iIcon As Integer           ' : icondex
        Public dwAttributes As Integer    ' : SFGAO_ flags
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)> _
        Public szDisplayName As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)>
        Public szTypeName As String
    End Structure

    Private Declare Ansi Function SHGetFileInfo Lib "shell32.dll" (ByVal pszPath As String, _
        ByVal dwFileAttributes As Integer, ByRef psfi As SHFILEINFO, ByVal cbFileInfo As Integer, _
        ByVal uFlags As Integer) As IntPtr

此外,我会丢​​失 On Error Goto 并使用 Try/Catch