Thursday, January 3, 2013

Extract icon from lnk file

Extract icon from lnk file


How could you extract the icon from a shortcut file (.lnk) in Windows programmatically with Visual Basic? How to remove the arrow in the icon from a shortcut file (.lnk)?

Inside Windows XP, Vista, Seven or Windows 8, the system automatically creates a new icon for every shortcut with the target file or the target folder and adds an arrow in it. If you don’t like the arrow on the icon in your shortcut, you will need to replace it by using the target file or target folder.
icon with arrow in shortcut


Unfortunally, each time you try to change it manually, Windows keeps creating a new icon with the arrow. The arrow could be easily be removed by changing some registry inside Windows.

The problem is when I use the ExtractAssociatedIcon from visual basic .NET (or C#.NET), I get the icon from the shortcut and not from the target file.


If System.IO.File.Exists(foundFile) Then

  If foundFile.Contains(".lnk") = True Then
        oIcon = System.Drawing.Icon.ExtractAssociatedIcon(foundFile)
  Else
        oIcon = System.Drawing.Icon.ExtractAssociatedIcon(foundFile)
  End If

  ImageList1.Images.Add(oIcon)
End If



icon with and without arrow in shortcut in treeview


The operation is not complicate because inside the lnk file, the target path is saved inside the shortcut file. You only need to use the target file path to get the real icon. You could use this code:


    Function GetTargetPath(ByVal FileName As String) As String

        Dim Obj As Object
        Obj = CreateObject("WScript.Shell")

        Dim Shortcut As Object
        Shortcut = Obj.CreateShortcut(FileName)
        GetTargetPath = Shortcut.TargetPath
        'Shortcut.Save()

    End Function


Feel free to download the sample code at the end of this post. That way you could play around the little sample program.
Please note something important on the previous function.  The Object Shortcut is ready only, so if you want to change the icon from the shortcut file, you need to create a new one.

Download sample code: SampleBasicProgram.zip


References:
Very good article on icons from MSDN :

No comments:

Post a Comment