Шустрый

Профиль
Группа: Участник
Сообщений: 83
Регистрация: 10.1.2007
Репутация: 1 Всего: 2
|
пришлось пару деньков вот что вышло | Код | using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Security; using Microsoft.Win32.SafeHandles; using System.Globalization; using System.IO; using System.Collections;
namespace resEdit { public partial class Form1 : Form { public Resource res = new Resource("e:\\qw\\PEFile.exe"); public Resource upRes = new Resource(); public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { pictureBox1.Image = res.GetIconResourceAsImage(new IntPtr((uint)1)); pictureBox2.Image = res.GetIconsResourceAsImage("#32512"); DllMethods.EnumResourceNames(res.hModule,new IntPtr((uint) ResourceType.RT_ICON), new DllMethods.EnumResourceNameDelegate(EnumRes), IntPtr.Zero); DllMethods.FreeLibrary(res.hModule); upRes.ProcessCmdLine("e:\\qw\\PEFile.exe", "e:\\qw\\www.txt", "txt",1); Load("e:\\qw\\qw3.ico"); }
public bool EnumRes(IntPtr hModule, IntPtr lpszType, IntPtr lpszName, IntPtr lParam) { Image img; img = res.GetIconResourceAsImage(lpszName); //img = res.GetIconsResourceAsImage(lpszName.ToString()); img.Save("d:\\" + lpszName + ".ico"); return true; }
public void Load(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); try { Load(fs); fs.Close(); } finally { if (fs != null) fs.Close(); } } public unsafe void Load(Stream stream) { ICONDIR ico = new ICONDIR(); ICONDIRENTRY ico2 = new ICONDIRENTRY(); byte[] array = new byte[sizeof(ICONDIR)]; stream.Read(array, 0, sizeof(ICONDIR)); fixed (byte* pData = array) ico = *(ICONDIR*)pData; BinaryReader br = new BinaryReader(stream); byte[] array2 = new byte[sizeof(ICONDIRENTRY)]; br.Read(array2, 0, sizeof(ICONDIRENTRY)); fixed (byte* pData = array2) ico2 = *(ICONDIRENTRY*)pData; br.Close(); InjectMainIcon("e:\\qw\\PEFile.exe", "e:\\qw\\qw3.ico", ico, ico2); }
public unsafe static void InjectMainIcon(string Where, string What, ICONDIR ico,ICONDIRENTRY ico2) { IntPtr hWhere = DllMethods.BeginUpdateResource(Where, false); BinaryReader hFile = new BinaryReader(File.OpenRead(What)); uint buffersizet = (uint)new FileInfo(What).Length; byte[] buffer = hFile.ReadBytes((int)buffersizet); hFile.Close(); byte[] buffer2 = new byte[buffersizet - 22]; for (int i = 0; i < buffersizet - 22; i++) { buffer2[i]= buffer[i + 22]; } DllMethods.UpdateResource(hWhere, 3, 1, 0, buffer2, (UInt32)buffersizet - 22); GROUPICON grData = new GROUPICON(); // This is the header grData.idReserved = ico.idReserved; grData.idType = ico.idType; grData.idCount = ico.idCount; // This is the directory entry grData.bWidth = ico2.bWidth; grData.bHeight = ico2.bHeight; grData.bColorCount = ico2.bColorCount; grData.bReserved = ico2.bReserved; grData.wPlanes = ico2.wPlanes; grData.wBitCount = ico2.wBitCount; grData.dwBytesInRes = buffersizet - 22; grData.dwImageOffset = 1;
DllMethods.UpdateResource(hWhere, 14, 32512, 0, &grData, sizeof(GROUPICON)); DllMethods.EndUpdateResource(hWhere, false); } } #region structs public struct ICONDIRENTRY // This is the Directory Entry stored in resources { public byte bWidth; public byte bHeight; public byte bColorCount; public byte bReserved; public ushort wPlanes; public ushort wBitCount; public uint dwBytesInRes; public uint dwImageOffset; } public struct ICONDIR { public UInt16 idReserved; public UInt16 idType; public UInt16 idCount; } [StructLayout(LayoutKind.Sequential, Pack = 2)] public struct GROUPICON { public UInt16 idReserved; // reserved, must be 0 public UInt16 idType; // type is 1 for icons public UInt16 idCount; // number of icons in structure (1) public byte bWidth; // icon width (32) public byte bHeight; // icon height (32) public byte bColorCount; // colors (0 means more than 8 bits per pixel) public byte bReserved; // reserved, must be 0 public ushort wPlanes; // color planes public ushort wBitCount; // bit depth public uint dwBytesInRes; // size of structure public uint dwImageOffset; // resource ID } #endregion
public static class ExternDll { public const string Kernel32 = "kernel32.dll"; public const string User32 = "user32.dll"; }
public unsafe static class DllMethods { [DllImport(ExternDll.Kernel32, CharSet = CharSet.Unicode, ExactSpelling = true, EntryPoint = "LoadLibraryExW")] public static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags);
[DllImport(ExternDll.Kernel32, ExactSpelling = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool FreeLibrary(IntPtr hModule);
[DllImport(ExternDll.Kernel32, CharSet = CharSet.Unicode, ExactSpelling = true, EntryPoint = "FindResourceExW")] public static extern IntPtr FindResourceEx(IntPtr hModule, IntPtr lpType, IntPtr lpId);
[DllImport(ExternDll.Kernel32, CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr FindResource(IntPtr hModule, IntPtr lpid,IntPtr lpType);
[DllImport(ExternDll.Kernel32, CharSet = CharSet.Unicode, SetLastError = true)] public static extern int SizeofResource(IntPtr hModule, IntPtr hResInfo);
[DllImport(ExternDll.Kernel32, CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern IntPtr LoadResource(IntPtr hModule, IntPtr hResInfo);
[DllImport(ExternDll.User32, EntryPoint = "LoadImageW", CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern IntPtr LoadImage(IntPtr hInst, string lpszName, uint uType, int cxDesired, int cyDesired, uint fuLoad);
[DllImport(ExternDll.Kernel32, CharSet = CharSet.Unicode, ExactSpelling = true)] public static extern IntPtr LockResource(IntPtr hResInfo); [DllImport(ExternDll.Kernel32, EntryPoint = "EnumResourceTypesW", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumResourceTypes(IntPtr hModule, EnumResourceTypeDelegate lpEnumFunc, IntPtr lParam);
[DllImport(ExternDll.Kernel32, EntryPoint = "EnumResourceNamesW", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumResourceNames(IntPtr hModule, IntPtr lpszType, EnumResourceNameDelegate lpEnumFunc, IntPtr lParam);
public delegate bool EnumResourceNameDelegate(IntPtr hModule, IntPtr lpszType, IntPtr lpszName, IntPtr lParam); public delegate bool EnumResourceTypeDelegate(IntPtr hModule, IntPtr lpszType, IntPtr lParam);
[DllImport(ExternDll.User32, SetLastError = true)] public static extern IntPtr CreateIconFromResource(IntPtr presbits, int dwResSize, bool fIcon, uint dwVer);
[DllImport(ExternDll.Kernel32, EntryPoint = "BeginUpdateResourceW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr BeginUpdateResource(string pFileName, bool bDeleteExistingResources);
[DllImport(ExternDll.Kernel32, EntryPoint = "UpdateResourceW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool UpdateResource(IntPtr hUpdate, UInt32 pType, UInt32 PName, UInt16 wLanguage, resEdit.GROUPICON* pData, int cbData);
[DllImport(ExternDll.Kernel32, EntryPoint = "UpdateResourceW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool UpdateResource(IntPtr hUpdate, string pType, UInt32 pName, UInt16 wLanguage, byte[] pData, UInt32 cbData); [DllImport(ExternDll.Kernel32, EntryPoint = "UpdateResourceW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool UpdateResource(IntPtr hUpdate, UInt32 pType, UInt32 pName, UInt16 wLanguage, byte[] pData, UInt32 cbData);
[DllImport(ExternDll.Kernel32, EntryPoint = "EndUpdateResourceW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool EndUpdateResource(IntPtr hUpdate, bool bDiscard); }
public enum ResourceType : uint { RT_ICON = 3, RT_ICONS = 14, }
public class Resource { public IntPtr hModule; private const uint DONT_RESOLVE_DLL_REFERENCES = 0x00000001; private const uint LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
public Resource(string filePathName) { hModule = DllMethods.LoadLibraryEx(filePathName, IntPtr.Zero, DONT_RESOLVE_DLL_REFERENCES | LOAD_LIBRARY_AS_DATAFILE); } private Hashtable table = new Hashtable(2); public Resource() { table.Add("RT_ICON", ResourceType.RT_ICON); table.Add("RT_ICONS", ResourceType.RT_ICONS); }
public Image GetIconResourceAsImage(IntPtr iconId) { IntPtr result = IntPtr.Zero; result = GetIconFromResource(iconId); if (result != IntPtr.Zero) return Icon.FromHandle(result).ToBitmap(); else return null; }
private IntPtr GetIconFromResource(IntPtr id) { int size = 0; IntPtr result = IntPtr.Zero; if (TryLockResource(ResourceType.RT_ICON, id, ref size, out result)) return DllMethods.CreateIconFromResource(result, size, true, 0x00030000); return result; }
protected bool TryLockResource(ResourceType Type, IntPtr Name, ref int resourceSize, out IntPtr result) {
result = DllMethods.FindResource(hModule,Name, new IntPtr((uint)Type)); if (result == IntPtr.Zero) return false; IntPtr hResData = DllMethods.LoadResource(hModule, result); if (hResData == IntPtr.Zero) return false; resourceSize = DllMethods.SizeofResource(hModule, result); if (resourceSize == 0) return false; result = DllMethods.LockResource(hResData); return true; }
public Image GetIconsResourceAsImage(string iconsId) { IntPtr result = IntPtr.Zero; result = GetImage(1, iconsId); if (result != IntPtr.Zero) return Icon.FromHandle(result).ToBitmap(); else return null; }
private IntPtr GetImage(uint type, string id) { uint u = 0; if (uint.TryParse(id, out u)) return DllMethods.LoadImage(hModule, "#" + id, type, 0, 0, 0x8000); return DllMethods.LoadImage(hModule, id, type, 0, 0, 0x8000); }
enum ResType { ResourceError = 0, // ошибка при определении типа ResourceIsNumber = 1, // тип задан числовым идентификатором ResourceIsString = 2 // тип задан строкой };
private ResType ResolveResource(string[] str, out uint nResType, out uint nResID) { nResType = 0; nResID = 0; try { nResID = Convert.ToUInt32(str[2]); } catch { return ResType.ResourceError; } try { if (table.ContainsKey(str[1])) { nResType = Convert.ToUInt32(table[str[1]]); } else nResType = Convert.ToUInt32(str[1]); } catch (Exception) { return ResType.ResourceIsString; } return ResType.ResourceIsNumber; }
private void UpdateResource(IntPtr hUpdate, string strResFile, string strResType, uint nResID) { using (BinaryReader reader = new BinaryReader(File.OpenRead(strResFile))) { long nCount = new FileInfo(strResFile).Length; byte[] bytes = reader.ReadBytes((int)nCount); reader.Close(); DllMethods.UpdateResource(hUpdate, strResType, nResID, 1049, bytes, (UInt32)nCount); } } private void UpdateResource(IntPtr hUpdate, string strResFile, uint nResType, uint nResID) { using (BinaryReader reader = new BinaryReader(File.OpenRead(strResFile))) { long nCount = new FileInfo(strResFile).Length; byte[] bytes = reader.ReadBytes((int)nCount); reader.Close();
DllMethods.UpdateResource(hUpdate, nResType, nResID, 0, bytes, (UInt32)nCount); } } private bool AppendResource(IntPtr hUpdate, string[] str) { try { uint nResType; uint nResID; ResType res = ResolveResource(str, out nResType, out nResID); if (res == ResType.ResourceError) return false; else { if (res == ResType.ResourceIsNumber) UpdateResource(hUpdate, str[0], nResType, nResID); else UpdateResource(hUpdate, str[0], str[1], nResID); } } catch { return false; } return true; } private bool AppendResource(IntPtr hUpdate, string strResourceInfo) { string[] str = null;
if (strResourceInfo.StartsWith("\"")) { int nIndex = strResourceInfo.LastIndexOf("\""); if (nIndex <= 0 || nIndex >= strResourceInfo.Length) return false;
string strResName = strResourceInfo.Substring(0, nIndex + 1); strResName = strResName.Replace('\"', ' ').Trim();
string strRest = strResourceInfo.Substring(nIndex + 2).Trim();
string[] strsRest = strRest.Split(new char[] { ' ', '\t' }); if (strsRest.Length != 2) return false;
str = new string[] { strResName, strsRest[0], strsRest[1] }; } else str = strResourceInfo.Split(new char[] { ' ', '\t' });
if (str == null || str.Length != 3) return false;
return AppendResource(hUpdate, str); }
public void ProcessCmdLine(string pFileName,string strResFile, string strResType, uint nResID) { try { IntPtr hUpdate = DllMethods.BeginUpdateResource(pFileName, false); if (hUpdate != IntPtr.Zero) { StringBuilder strb = new StringBuilder(); strb.AppendFormat("\"{0}\" {1} {2}", new object[] { strResFile, strResType, nResID }); DllMethods.EndUpdateResource(hUpdate, !AppendResource(hUpdate, strb.ToString())); } } catch { return; } } } }
|
Код ужасен  , это просто мой черновой вариант. Тут показано как читать и писать иконки в ЕХЕ, а также находить ресурсы без знания их имен в ЕХЕ. При записи в ЕХЕ иконки рассмотрен вариант что в формате иконке только один вид отображения, но их может быть и больше. Надеюсь эта инфа быстро поможет разобраться с иконками и ресурсами.
|