Overview
Changing the icon in your .exe file is straightforward though a bit cumbersome. You'll potentially need to do three things:
- Prevent your running process from holding a lock on the .exe file which would prevent it from being modified
- Possibly modify file permissions to make it writable
- Actually edit the .exe file to replace the icon
Details
Step 3 - actually editing the .exe file - is the most interesting, so I'll start there. You will use the BeginUpdateResource()
, UpdateResource()
and EndUpdateResource()
calls in kernel32.dll
. Basically you do this:
byte[] data = File.ReadAllBytes(newIconFilePath);
// Or otherwise load icon data
IntPtr hUpdate = BeginUpdateResource(exePath, false);
UpdateResource(hUpdate, RT_ICON, MAKEINTRESOURCE(1), LANG_SYSTEM_DEFAULT,
data, data.Length);
EndUpdateResource(hUpdate, false);
You'll need to add DllImport
declarations for the functions and implement the constants. See the documentation on MSDN for details on how BeginUpdateResource
, UpdateResource
, and EndUpdateResource
work.
For step 1 - preventing your .exe from being locked - the easy solution is to add code to your application startup that checks to see if the current .exe is running from the temporary directory (Path.GetTempPath()
). If not, it copies the .exe to the temporary directory using File.Copy()
along with any additional files needed, then executes it with one additional command line argument that gives the location of the original .exe. The original process then exits, removing the lock on the .exe file.
For step 2 - correcting permissions - this simply a matter of modifying the ACLs and possibly triggering a UAC dialog. There are plenty of examples out there and you probably don't need to do this, so I'll skip further explanation
Final note
The above steps will actually allow you to edit the actual icon of your real .exe file. However if you just need a visual icon change I would recommend you use a shortcut and edit its icon instead.