Don't like ads? PRO users don't see any ads ;-)
Guest

Using UpdateResource in C#

By: a guest on Feb 22nd, 2012  |  syntax: None  |  size: 1.62 KB  |  hits: 204  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. class IconChanger
  2. {
  3.     [DllImport("kernel32.dll", SetLastError = true)]
  4.     static extern IntPtr BeginUpdateResource(string pFileName,
  5.         [MarshalAs(UnmanagedType.Bool)]bool bDeleteExistingResources);
  6.  
  7.     [DllImport("kernel32.dll", SetLastError = true)]
  8.     static extern bool UpdateResource(IntPtr hUpdate, string lpType, string lpName, ushort wLanguage,
  9.         IntPtr lpData, uint cbData);
  10.  
  11.     [DllImport("kernel32.dll", SetLastError = true)]
  12.     static extern bool EndUpdateResource(IntPtr hUpdate, bool fDiscard);
  13.  
  14.     public enum ICResult
  15.     {
  16.         Success,
  17.         FailBegin,
  18.         FailUpdate,
  19.         FailEnd
  20.     }
  21.  
  22.     public ICResult ChangeIcon(string exeFilePath, byte[] iconData)
  23.     {
  24.         // Load executable
  25.         IntPtr handleExe = BeginUpdateResource(exeFilePath, false);
  26.  
  27.         if (handleExe == null)
  28.             return ICResult.FailBegin;
  29.  
  30.         // Get language identifier
  31.         CultureInfo currentCulture = CultureInfo.CurrentCulture;
  32.         int pid = ((ushort)currentCulture.LCID) & 0x3ff;
  33.         int sid = ((ushort)currentCulture.LCID) >> 10;
  34.         ushort languageID = (ushort)((((ushort)pid) << 10) | ((ushort)sid));
  35.  
  36.         // Get pointer to data
  37.         GCHandle iconHandle = GCHandle.Alloc(iconData, GCHandleType.Pinned);
  38.  
  39.         // Replace the icon
  40.         if (UpdateResource(handleExe, "#3", "#1", languageID, iconHandle.AddrOfPinnedObject(), (uint)iconData.Length))
  41.         {
  42.             if (EndUpdateResource(handleExe, false))
  43.                 return ICResult.Success;
  44.             else
  45.                 return ICResult.FailEnd;
  46.         }
  47.         else
  48.             return ICResult.FailUpdate;
  49.     }
  50. }