如何在Windows Mobile下使用.NET Compact Framework从执行文件取出Icon

需求

需要把其他执行文件的ICON读取出来,然后在程序中显示。

 

实现

class ExtractIcon
{
public static Bitmap GetBitmapFromExeIcon(string path)
{
return GetBitmap(GetIconFromExe(path));
}

public static Icon GetIconFromExe(string path)
{
return GetIconFromExe(path, true);
}

//http://www.pinvoke.net/default.aspx/shell32/ExtractIconEx.html
public static Icon GetIconFromExe(string path, bool large)
{
IntPtr hLargeIcon = IntPtr.Zero;
IntPtr hSmallIcon = IntPtr.Zero;
ExtractIconEx(path, 0, ref hLargeIcon, ref hSmallIcon, 1);
if (large)
{
return (Icon)Icon.FromHandle(hLargeIcon).Clone();
}
else
{
return (Icon)Icon.FromHandle(hSmallIcon).Clone();
}
}

//http://social.msdn.microsoft.com/Forums/en-US/netfxcompact/thread/e765775c-a5b5-493f-baeb-3eaee1d41cef
public static Bitmap GetBitmap(Icon icon)
{
Bitmap bmp = new Bitmap(icon.Width, icon.Height);

//Create temporary graphics
Graphics gxMem = Graphics.FromImage(bmp);

//Draw the icon
gxMem.DrawIcon(icon, 0, 0);

//Clean up
gxMem.Dispose();

return bmp;
}

//http://msdn.microsoft.com/en-us/library/aa922154.aspx
[DllImport("coredll.dll", SetLastError = true)]
private static extern IntPtr ExtractIconEx(string fileName, int index, ref IntPtr hIconLarge, ref IntPtr hIconSmall, uint nIcons);
}

MS提供了ExtractIconEx函数可以取出执行文件的大小Ico图标信息。第三个参数为大图标,第四个参数为小图标。

由于Icon对象不能直接在Graphics上画,所以需要转换成Bitmap,但是Compact Framework又不支持Icon.Save(),所以实现了一个Bitmap GetBitmap(Icon icon) 函数。

效果图如下,取出word的图标。

ico1

第二个图去掉ico背景

posted @   Jake Lin  阅读(1427)  评论(8编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示