首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在C#项目中使用shell32.dll中的图像?

如何在C#项目中使用shell32.dll中的图像?
EN

Stack Overflow用户
提问于 2011-07-29 20:20:17
回答 5查看 14.1K关注 0票数 10

如何在C#项目中使用shell32.dll中的图像?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-07-29 20:25:17

您可以使用以下代码从DLL中提取图标:

代码语言:javascript
复制
public class IconExtractor
{

    public static Icon Extract(string file, int number, bool largeIcon)
    {
        IntPtr large;
        IntPtr small;
        ExtractIconEx(file, number, out large, out small, 1);
        try
        {
            return Icon.FromHandle(largeIcon ? large : small);
        }
        catch
        {
            return null;
        }

    }
    [DllImport("Shell32.dll", EntryPoint = "ExtractIconExW", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
    private static extern int ExtractIconEx(string sFile, int iIndex, out IntPtr piLargeVersion, out IntPtr piSmallVersion, int amountIcons);

}

...

form.Icon = IconExtractor.Extract("shell32.dll", 42, true);

当然,您需要知道DLL中图像的索引...

票数 18
EN

Stack Overflow用户

发布于 2011-07-29 20:25:38

MSDN开发者论坛上的This thread提供了一个解决方案:

在.NET中实现这些的典型方法是使用位于C:\Program Files\Microsoft Visual Studio \Common7\VS200XImageLibrary的

文件中提供的图形。

您没有说明您安装了哪个版本的Visual Studio,但您需要将"200X“替换为您的版本号。

票数 3
EN

Stack Overflow用户

发布于 2020-06-22 04:44:49

接受应答中的代码在每次调用时都会泄漏一个图标句柄,因为它总是请求两个图标句柄,而只返回一个图标句柄。

下面是一个不会泄漏句柄的版本:

代码语言:javascript
复制
public static Icon Extract(string filePath, int index, bool largeIcon = true)
{
    if (filePath == null)
        throw new ArgumentNullException(nameof(filePath));

    IntPtr hIcon;
    if (largeIcon)
    {
        ExtractIconEx(filePath, index, out hIcon, IntPtr.Zero, 1);
    }
    else
    {
        ExtractIconEx(filePath, index, IntPtr.Zero, out hIcon, 1);
    }

    return hIcon != IntPtr.Zero ? Icon.FromHandle(hIcon) : null;
}

[DllImport("shell32", CharSet = CharSet.Unicode)]
private static extern int ExtractIconEx(string lpszFile, int nIconIndex, out IntPtr phiconLarge, IntPtr phiconSmall, int nIcons);

[DllImport("shell32", CharSet = CharSet.Unicode)]
private static extern int ExtractIconEx(string lpszFile, int nIconIndex, IntPtr phiconLarge, out IntPtr phiconSmall, int nIcons);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6872957

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档