c#怎么实现一个替换exe图标的功能,如qq.exe图标替换成酷狗的ico。
发布网友
发布时间:2022-07-10 14:07
我来回答
共1个回答
热心网友
时间:2023-10-14 06:10
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
struct ICONDIRENTRY
{
byte bWidth;
byte bHeight;
byte bColorCount;
byte bReserved;
short wPlanes;
short wBitCount;
public int dwBytesInRes;
public int dwImageOffset;
};
struct ICONDIR
{
short idReserved;
short idType;
public short idCount;
//ICONDIRENTRY idEntries;
};
struct GRPICONDIRENTRY
{
byte bWidth;
byte bHeight;
byte bColorCount;
byte bReserved;
short wPlanes;
short wBitCount;
int dwBytesInRes;
public short nID;
};
struct GRPICONDIR
{
public short idReserved;
public short idType;
public short idCount;
public GRPICONDIRENTRY idEntries;
};
class Program
{
[DllImport("kernel32.dll")]
public static extern IntPtr BeginUpdateResourceW([In] [MarshalAs(UnmanagedType.LPWStr)] string pFileName, [MarshalAs(UnmanagedType.Bool)] bool bDeleteExistingResources);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern unsafe bool UpdateResourceW([In] IntPtr hUpdate, [In] char* lpType, [In] char* lpName, ushort wLanguage, [In] IntPtr lpData, uint cb);
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EndUpdateResourceW([In] IntPtr hUpdate, [MarshalAs(UnmanagedType.Bool)] bool fDiscard);
public static T ToStruct<T>(byte[] bytes, int index) where T : struct
{
int size = Marshal.SizeOf(typeof(T));
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, index, buffer, size);
return (T)Marshal.PtrToStructure(buffer, typeof(T));
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
public static unsafe void Main(string[] args)
{
var exe = @"f:\SkypeSetup.exe";
var ico = "f:\\1.ico";
var RT_ICON = 3;
var DIFFERENCE = 11;
var RT_GROUP_ICON = (RT_ICON + DIFFERENCE);
var p = BeginUpdateResourceW(exe, false);
var ico2 = File.ReadAllBytes(ico);
var stID = ToStruct<ICONDIR>(ico2, 0);
var stIDE = ToStruct<ICONDIRENTRY>(ico2, Marshal.SizeOf(typeof(ICONDIR)));
var nSize = stIDE.dwBytesInRes;
var pIcon = Marshal.AllocHGlobal(nSize);
Marshal.Copy(ico2, stIDE.dwImageOffset, pIcon, nSize);
var stGID = new GRPICONDIR();
stGID.idCount = stID.idCount;
stGID.idReserved = 0;
stGID.idType = 1;
stGID.idEntries = ToStruct<GRPICONDIRENTRY>(ico2, Marshal.SizeOf(typeof(ICONDIR)));
stGID.idEntries.nID = 0;
var nGSize = Marshal.SizeOf(typeof(GRPICONDIR));
var pGrpIcon = Marshal.AllocHGlobal(nGSize);
Marshal.StructureToPtr(stGID, pGrpIcon, false);
var b = UpdateResourceW(p, (char*)RT_GROUP_ICON, (char*)1, 0, pGrpIcon, (uint)nGSize);
b = UpdateResourceW(p, (char*)RT_ICON, (char*)1, 0, pIcon, (uint)nSize);
EndUpdateResourceW(p, false);
Marshal.FreeHGlobal(pIcon);
}
}
}
需要用到不安全代码