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

时间:2016-07-11 04:07:45

标签: vb.net shell32.dll

我的代码存在以下问题。

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时,它返回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 

你能帮助我找出问题所在吗?

谢谢

1 个答案:

答案 0 :(得分:1)

尝试将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