c# - 获取给定扩展的图标

标签 c#

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

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());
}

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

最佳答案

使用 this 中的 GetFileIcon 方法Paul Ingles 的 CodeProject 文章并将 .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;
}

关于c# - 获取给定扩展的图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28454419/

相关文章:

c# - ReSharper C# Intellisense 在键入 Override 关键字后显示可覆盖的成员

c# - 如何使用javascript点击页面上的json超链接

c# - 使用 Json.NET 序列化后的程序集卸载

c# - 让VisualStudio运行命令生成C#代码

c# - DropDownList asp.net 中所选项目的文本

c# - 格式化 XML 字符串以打印友好的 XML 字符串

c# - 如何检查自定义模型 Binder 中的属性属性

c# - 如何将 Azure AD 身份验证添加到现有 .net 网站

c# - Azure 服务总线 - 多个主题?

c# - 如何确定一首歌曲使用了 winmm.dll 多长时间?