We create an shortcut in the start menu of windows and for that shortcut we want to apply the icon of the target file. The target file is an help file of Help & Manual (Suffix is .chm). We tried the following code:
var lPath = @"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\ProductName\Help.lnk";
var lTargetPath = @"C:\Program Files\ManufacturerName\ProductName\Help.chm";
WshShell lWshShell = new WshShell();
IWshShortcut lShortcut = (IWshShortcut)lWshShell.CreateShortcut(lPath);
lShortcut.WorkingDirectory = lPath;
lShortcut.TargetPath = lTargetPath;
lShortcut.IconLocation = lTargetPath; // <-- I want to apply the same icon as the target file here.
The target .chm file has the followin icon:
When we execute this code, the shortcut in the start menu looks like the following:
How can we automatically apply the icon of the target file?
NOTE: When I create an shortcut via WIX using the same paths, then the icon will be applied to the shortcut.
I was under the impression that the icon for any file in Windows is the icon associated with the .exe
of the program that would open such file by default (i.e. file associations and default programs). For shortcuts, the default should be to follow the symlink and present whatever icon the target itself has, unless you override it.
My guess is that the line lShortcut.IconLocation = lTargetPath;
sets the icon to something that is not a valid icon, but Windows will still try to honour it and fall back to the default "blank" icon that you see. Do note that the .chm
file itself has no icon and is not an icon. The icon shown is merely that of the system's help viewer.
I just tested this manually. Create a .txt
file on your Desktop and verify it has an icon. Then right-click it and choose Send To -> Desktop (Create Shortcut)
to create the shortcut. It will have the same icon. Right-click the shortcut, choose Properties
, then Set Icon...
and type in any path. Press OK
, dismiss the warning, press OK
again.
For me, the icon changed from Notepad++'s icon (my default for .txt
files) to the blank file icon.
When I choose "Set Icon" the next time on the shortcut, Windows will first present a warning that my previously set invalid path cannot be found, so this proved that whatever you fill in, is saved somewhere, regardless of whether it's valid.