我知道我可以使用提取文件的图标

using (System.Drawing.Icon sysicon = System.Drawing.Icon.ExtractAssociatedIcon(filePath))
{
    icon = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(
        sysicon.Handle,
        System.Windows.Int32Rect.Empty,
        System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}

但是我如何在没有文件的情况下获取给定扩展名的图标?

最佳答案

使用Paul Ingles的this CodeProject文章中的GetFileIcon方法,并将.ext传递为name参数。
GetFileIcon方法是对本地 SHGetFileInfo 的包装,并在此处复制以用于说明:

public static System.Drawing.Icon GetFileIcon(string name, IconSize size,
                                              bool linkOverlay)
{
    Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO();
    uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES;

    if (true == linkOverlay) flags += Shell32.SHGFI_LINKOVERLAY;


    /* Check the size specified for return. */
    if (IconSize.Small == size)
    {
        flags += Shell32.SHGFI_SMALLICON ; // include the small icon flag
    }
    else
    {
        flags += Shell32.SHGFI_LARGEICON ;  // include the large icon flag
    }

    Shell32.SHGetFileInfo( name,
        Shell32.FILE_ATTRIBUTE_NORMAL,
        ref shfi,
        (uint) System.Runtime.InteropServices.Marshal.SizeOf(shfi),
        flags );


    // Copy (clone) the returned icon to a new object, thus allowing us
    // to call DestroyIcon immediately
    System.Drawing.Icon icon = (System.Drawing.Icon)
                         System.Drawing.Icon.FromHandle(shfi.hIcon).Clone();
    User32.DestroyIcon( shfi.hIcon ); // Cleanup
    return icon;
}

10-07 20:33