private static void ReplaceExeIco(string exepath, string icopath)
{
try
{
FileStream fileStream = new FileStream(icopath, FileMode.Open, FileAccess.Read);
byte[] fileByte = new byte[fileStream.Length];
fileStream.Read(fileByte, 0, fileByte.Length);
Int32 lOffset = 0;
uint dwSize = 0;
byte[] bytesize = new byte[sizeof(uint)];
Array.Copy(fileByte, 0x0e, bytesize, 0, sizeof(uint));
//icon文件数据长度(文件格式加图标数据)
dwSize = BitConverter.ToUInt32(bytesize, 0);
byte[] offsetbytes = new byte[sizeof(Int32)];
Array.Copy(fileByte, 0x12, offsetbytes, 0, sizeof(uint));
//icon文件格式长度(22位)
lOffset = BitConverter.ToInt32(offsetbytes, 0);
byte[] lpRes = new byte[dwSize];
//获取icon文件图标数据
Array.Copy(fileByte, lOffset, lpRes, 0, dwSize);
const uint RT_ICON = 3;
IntPtr hApp = BeginUpdateResource(exepath, false);
if (hApp == IntPtr.Zero)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
//更新资源数据,RT_ICON是指更新图标,1是指图标名称可通过API获取或eXeScope查询,网上很多地方都有额外
//进行UpdateResource(hApp, RT_GROUP_ICON, 1, 0, lpGroupIco, bGroupIcoSize)(RT_GROUP_ICON=14)的更新,
//但通过eXeScope查看发现,更新RT_GROUP_ICON会在资源图标中新增1个空图标,exe文件会使用空图标,导致更
//换图标失效
if (UpdateResource(hApp, RT_ICON, 1, 0, lpRes, dwSize) != 1)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
if (!EndUpdateResource(hApp, false))
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
catch (Exception ex)
{
}
}
更新后需要刷新系统的图标缓存才能实时更新显示,否则需要重启电脑
刷新缓存做法(赋值下面的文本到文本文件中,将文本文件更改为.bat文件,运行.bat文件):
rem 关闭Windows外壳程序explorer
taskkill /f /im explorer.exe
rem 清理系统图标缓存数据库
attrib -h -s -r "%userprofile%\AppData\Local\IconCache.db"
del /f "%userprofile%\AppData\Local\IconCache.db"
attrib /s /d -h -s -r "%userprofile%\AppData\Local\Microsoft\Windows\Explorer\*"
del /f "%userprofile%\AppData\Local\Microsoft\Windows\Explorer\thumbcache_32.db"
del /f "%userprofile%\AppData\Local\Microsoft\Windows\Explorer\thumbcache_96.db"
del /f "%userprofile%\AppData\Local\Microsoft\Windows\Explorer\thumbcache_102.db"
del /f "%userprofile%\AppData\Local\Microsoft\Windows\Explorer\thumbcache_256.db"
del /f "%userprofile%\AppData\Local\Microsoft\Windows\Explorer\thumbcache_1024.db"
del /f "%userprofile%\AppData\Local\Microsoft\Windows\Explorer\thumbcache_idx.db"
del /f "%userprofile%\AppData\Local\Microsoft\Windows\Explorer\thumbcache_sr.db"
rem 重启Windows外壳程序explorer
start explorer