C# .exe和.dll文件图标资源提取工具

Windows 可执行文件(.exe)和动态库文件(.dll)图标资源提取工具

GitHub

截图

功能

  • 图标资源预览
  • 图标资源导出(仅支持导出 PNG 格式)

代码

获取图标资源使用了 Win32 API PrivateExtractIconsW

PrivateExtractIconsW 对应的 C# 代码

[DllImport("User32.dll")]
internal static extern uint PrivateExtractIcons(
    /* _In_reads_(MAX_PATH) */ string szFileName,
    /* _In_ */ int nIconIndex,
    /* _In_ */ int cxIcon,
    /* _In_ */ int cyIcon,
    /* _Out_writes_opt_(nIcons) */ IntPtr[] phicon,
    /* _Out_writes_opt_(nIcons) */ uint[] piconid,
    /* _In_ */ uint nIcons,
    /* _In_ */ uint flags);

参数:

szFileName 要从中提取图标的文件的路径和名称。

nIconIndex 要提取的第一个图标的从零开始的索引。例如,如果此值为零,则该函数会提取指定文件中的第一个图标。

cxIcon 想要的水平图标大小。

cyIcon 想要的垂直图标大小。

phicon 指向返回的图标句柄数组的指针。

piconid 指向最适合当前显示设备的图标的返回资源标识符的指针。

nIcons 要从文件中提取的图标数。此参数仅在从 .exe 和 .dll 文件中提取时有效。

flags 指定控制此功能的标志。

主要步骤

  1. 需要先获取文件中的图标总数量。phicon 参数为 NULL,返回值为文件中的图标数
int _nIcons = PrivateExtractIcons(filePath, 0, 0, 0, null, null, 0, 0);
  1. 获取所有图标资源句柄。返回值为获取到的图标数量
IntPtr[] phicon = new IntPtr[_nIcons];
uint[] piconid = new uint[_nIcons];
uint nIcons = PrivateExtractIcons(filePath, 0, 32, 32, phicon, piconid, _nIcons, 0);
  1. 转换成位图。需要释放资源
for (int i = 0; i < nIcons; i++)
{
    Icon icon = Icon.FromHandle(phicon[i]);
    Bitmap bitmap = icon.ToBitmap();
    icon.Dispose();

    _ = DestroyIcon(phicon[i]);
}
posted @ 2021-06-23 12:57  he55  阅读(1752)  评论(0编辑  收藏  举报