开发者

Icon.ExtractAssociatedIcon for things that are not files?

Is this possible? It gives me an error, and I had previously thought it could work for folders and drives and stuff like that as well.

Icon.ExtractAssociatedIcon("C:\") did not work when I tried it, and threw an error.

How can I get the associated icon from EVERYTHI开发者_如何学编程NG? This is vb.net


The SHGetFileInfo() shell function can provide you with the icon you are looking for. This code worked well, it generated appropriate icons for drives, folders and files:

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


It is not possible to use Icon.ExtractAssociatedIcon on anything other than files. This API is a thin wrapper on top of the Win32 call ExtractAssociatedIcon. While the documentation for the managed code is a bit ambiguous, the native documentation is much clearer that the target must be a file. It goes further to say that it must be an executable file.

Unfortunately I'm not sure if there is an equivalent function for Directories or not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜