Unity 读取exe文件图标
工程需要导入 System.Drawing.dll, 位置可百度
以下两个方式都可调用。
1、public class LoadExeIcon{
private static extern int ExtractAssociatedIconA(int hInst, string lpIconPath, ref int lpiIcon); //声明函数
static System.IntPtr thisHandle;
public static System.Drawing.Bitmap GetIcon(string path)
{
int RefInt = 0;
thisHandle = new IntPtr(ExtractAssociatedIconA(0, path, ref RefInt));
System.Drawing.Bitmap image = System.Drawing.Icon.FromHandle(thisHandle).ToBitmap();
return image;
}
}
2、
直接添加函数 ,传入参数为文件名称(可全路径)
public static Icon GetIconByFileName(string fileName, bool isLarge = true)
{
int[] phiconLarge = new int[1];
int[] phiconSmall = new int[1];
//文件名 图标索引
DllOpenFileDialog.ExtractIconEx(fileName, 0, phiconLarge, phiconSmall, 1);
IntPtr IconHnd = new IntPtr(isLarge ? phiconLarge[0] : phiconSmall[0]);
return Icon.FromHandle(IconHnd);
}
调用方式:
System.Drawing.Bitmap bmp = DllOpenFileDialog.GetIcon(“E:\hfs.exe”);
//System.Drawing.Bitmap bmp = GetIconByFileName(“E:\hfs.exe”, false).ToBitmap();
// bitmap转Unity sprite
MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Png);
var buffer = new byte[ms.Length];
ms.Position = 0;
ms.Read(buffer, 0, buffer.Length);
Texture2D newTex = new Texture2D(1, 1);
newTex.LoadImage(buffer);
Sprite s = Sprite.Create(newTex, new Rect(0, 0, newTex.width, newTex.height), Vector2.zero);