如何在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 @ 2009-08-11 11:22  Jake Lin  阅读(1424)  评论(8编辑  收藏  举报