Icon.ExtractAssociatedIcon用于非文件的东西?

时间:2009-10-11 17:55:28

标签: vb.net

这可能吗?它给了我一个错误,我以前认为它可以用于文件夹和驱动器以及类似的东西。

Icon.ExtractAssociatedIcon(“C:\”)在我尝试时无法正常工作,并引发了错误。

如何从一切中获取相关图标?这是vb.net

2 个答案:

答案 0 :(得分:5)

SHGetFileInfo()shell函数可以为您提供所需的图标。此代码运行良好,它为驱动器,文件夹和文件生成了适当的图标:

Imports System.Drawing
Imports System.Reflection
Imports System.Runtime.InteropServices

Public Module NativeMethods
  Public Function GetShellIcon(ByVal path As String) As Icon
    Dim info As SHFILEINFO = New SHFILEINFO()
    Dim retval as IntPtr = SHGetFileInfo(path, 0, info, Marshal.SizeOf(info), &H100)
    If retval = IntPtr.Zero Then Throw New ApplicationException("Could not retrieve icon")
    '' Invoke private Icon constructor so we do not have to copy the icon
    Dim cargt() As Type = { GetType(IntPtr) }
    Dim ci As ConstructorInfo = GetType(Icon).GetConstructor(BindingFlags.NonPublic Or BindingFlags.Instance, Nothing, cargt, Nothing)
    Dim cargs() As Object = { info.IconHandle }
    Dim icon As Icon = CType(ci.Invoke(cargs), Icon)
    Return icon
  End Function

  '' P/Invoke declaration
  Private Structure SHFILEINFO
    Public IconHandle As IntPtr
    Public IconIndex As Integer
    Public Attributes As Integer
    <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)> _
    Public DisplayString As String
    <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=80)> _
    Public TypeName As String
  End Structure

  Private Declare Auto Function SHGetFileInfo lib "Shell32.dll" (path As String, _
    attributes As Integer, byref info As SHFILEINFO, infoSize As Integer, flags As Integer) As IntPtr

End Module

答案 1 :(得分:1)

无法在文件以外的任何内容上使用Icon.ExtractAssociatedIcon。此API是Win32调用ExtractAssociatedIcon之上的瘦包装器。虽然托管代码的文档有点模糊,但本机文档更清晰,目标必须是文件。它进一步说它必须是一个可执行文件。

不幸的是,我不确定目录是否有相同的功能。