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

Cyc*_*one 4 vb.net

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

当我尝试它时,Icon.ExtractAssociatedIcon("C:\")不起作用,并抛出一个错误.

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

Han*_*ant 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
Run Code Online (Sandbox Code Playgroud)

  • @Jazimov可能有点晚了,但在这里:https://gist.github.com/D4koon/2b397eca452b75115f19063560efbbb3 (2认同)