Шустрый

Профиль
Группа: Участник
Сообщений: 83
Регистрация: 10.1.2007
Репутация: 1 Всего: 2
|
Цитата(mr.DUDA @ 9.7.2006, 23:29 ) | Да нифига, я посмотрел, действительно неправильно всё работает... И что самое обидное - ведь когда давал ответ в тему (Ch0bits оттуда пример достал), всё работало ! А тут даже SizeofResource неправильно отрабатывает ! |
Все прекрасно работает, просто надо коечто было дописать. Код | 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("d:\\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)2)); 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("d:\\qw\\PEFile.exe", "c:\\55.ico", "14",32512); }
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 static class ExternDll { public const string Kernel32 = "kernel32.dll"; public const string User32 = "user32.dll"; }
public 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 lpType, IntPtr lpid);
[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, 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, string 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 (Exception ex) { 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, 1049, 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 (Exception ex) { 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; } } } }
|
Только возник вопрос. Если в студии добавить иконку то она записывается в двух видах RT_ICON, RT_ICONS. Я пытался перезаписать эти ресурсы, но не получается. Если перезаписывать ресурс RT_ICONS то он создает туже иконку но с языком рус., а RT_ICON вообще не меняет. Только вот если с другим именем все прекрасно пишется, но тогда пропадает иконка вообще и она хоть и записывается как икона (только под другим именем), но при обратном считывание это обычный файл. Суть такая как правильно перезаписать иконку?? Это сообщение отредактировал(а) Dino99rus - 22.8.2008, 18:32
|