public IconFile FromFile(string filename) { byte[] fileBytes = System.IO.File.ReadAllBytes(filename); GCHandle pinnedBytes = GCHandle.Alloc(fileBytes, GCHandleType.Pinned); IconFile instance = new IconFile(); { iconDir = (IconInjector.ICONDIR)Marshal.PtrToStructure(pinnedBytes.AddrOfPinnedObject(), typeof(IconInjector.ICONDIR)); iconEntry = new IconInjector.ICONDIRENTRY[instance.iconDir.Count]; iconImage = new byte[instance.iconDir.Count][]; } int offset = Marshal.SizeOf(instance.iconDir); Type iconDirEntryType = typeof(IconInjector.ICONDIRENTRY); int size = Marshal.SizeOf(iconDirEntryType); for (int i = 0; i < instance.iconDir.Count - 1; i++) { IconInjector.ICONDIRENTRY entry = (IconInjector.ICONDIRENTRY) Marshal.PtrToStructure(new IntPtr(pinnedBytes.AddrOfPinnedObject().ToInt64() + offset), iconDirEntryType); instance.iconEntry[i] = entry; instance.iconImage[i] = new byte[entry.ByteInRes]; Buffer.BlockCopy(fileBytes, entry.ImageOffset, instance.iconImage[i], 0, entry.ByteInRes); offset += size; } pinnedBytes.Free(); return instance; }
public IconFile FromFile(string filename) { byte[] fileBytes = System.IO.File.ReadAllBytes(filename); GCHandle pinnedBytes = GCHandle.Alloc(fileBytes, GCHandleType.Pinned); IconFile instance = new IconFile(); { iconDir = (IconInjector.ICONDIR)Marshal.PtrToStructure(pinnedBytes.AddrOfPinnedObject(), typeof(IconInjector.ICONDIR)); iconEntry = new IconInjector.ICONDIRENTRY[instance.iconDir.Count]; iconImage = new byte[instance.iconDir.Count][]; } int offset = Marshal.SizeOf(instance.iconDir); Type iconDirEntryType = typeof(IconInjector.ICONDIRENTRY); int size = Marshal.SizeOf(iconDirEntryType); for (int i = 0; i < instance.iconDir.Count - 1; i++) { IconInjector.ICONDIRENTRY entry = (IconInjector.ICONDIRENTRY) Marshal.PtrToStructure(new IntPtr(pinnedBytes.AddrOfPinnedObject().ToInt64() + offset), iconDirEntryType); instance.iconEntry[i] = entry; instance.iconImage[i] = new byte[entry.ByteInRes]; Buffer.BlockCopy(fileBytes, entry.ImageOffset, instance.iconImage[i], 0, entry.ByteInRes); offset += size; } pinnedBytes.Free(); return(instance); }
public static void InjectIcon(string exeFileName, string iconFileName, int iconGroupID, uint iconBaseID) { const uint RT_ICON = 3; IntPtr RT_GROUP_ICON = new IntPtr(14); IconFile iconFile = new IconFile().FromFile(iconFileName); IntPtr hUpdate = NativeMethods.BeginUpdateResource(exeFileName, false); byte[] data = iconFile.CreateIconGroupData(iconBaseID); NativeMethods.UpdateResource( hUpdate, RT_GROUP_ICON, new IntPtr(iconGroupID), 0, data, data.Length); for (int i = 0; i < iconFile.ImageCount - 1; i++) { byte[] image = iconFile.ImageData(i); NativeMethods.UpdateResource(hUpdate, new IntPtr(RT_ICON), new IntPtr(iconBaseID + i), 0, image, image.Length); } NativeMethods.EndUpdateResource(hUpdate, false); }