Extract Icon from Windows .lnk (shortcut) file
Solution 1:
Using the Shell32 method of acessing links:
String lnkPath = @"C:\Users\PriceR\Desktop\Microsoft Word 2010.lnk";
//--- run microsoft word
var shl = new Shell32.Shell(); // Move this to class scope
lnkPath = System.IO.Path.GetFullPath(lnkPath);
var dir = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath));
var itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath));
var lnk = (Shell32.ShellLinkObject)itm.GetLink;
//lnk.GetIconLocation(out strIcon);
String strIcon;
lnk.GetIconLocation(out strIcon);
Icon awIcon = Icon.ExtractAssociatedIcon(strIcon);
this.button1.Text = "";
this.button1.Image = awIcon.ToBitmap();
Solution 2:
This thread provides interesting informations about the data contained in a .lnk file
The sSHGetFileInfoss function should be able to extract the icon file.
Documented here, and used for a lnk file:
Path2Link := 'C:\Stuff\TBear S Saver.lnk';
SHGetFileInfo(PChar(Path2Link), 0, ShInfo1, SizeOf(TSHFILEINFO),
SHGFI_ICON);
// this ShInfo1.hIcon will have the Icon Handle for the Link Icon with
// the small ShortCut arrow added}
From the first link, you could build such an utility in c#, where you would declare this function like:
[DllImport("shell32.dll")]
public static extern IntPtr SHGetFileInfo(
string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi,
uint cbSizeFileInfo, uint uFlags);
You could also built an utility in autoit script language, where you would use that function declared like this:
Func _ShellGetAssocIcon(Const $szFile,Const $IconFlags = 0)
Local $tFileInfo = DllStructCreate($tagSHFILEINFO)
If @error Then
Return SetError(1,@extended,0)
EndIf
Local $Ret = DllCall("shell32.dll","int","SHGetFileInfo","str",$szFile,"dword",0, _
"ptr",DllStructGetPtr($tFileInfo),"uint",DllStructGetSize($tFileInfo),"uint",BitOr($SHGFI_ICON,$IconFlags))
MsgBox(0,0,@error)
Return DllStructGetData($tFileInfo,"hIcon")
EndFunc
Solution 3:
In 2010 Microsoft finally released an official specification of the LNK file format. It much more accurate and detailed than the reverse-engineered specs floating around the net, of course.
For completeness sake, here is the MSDN description of shell links and shortcuts.