pythonwindowsiconslnk

change the icon of a windows shortcut .lnk file using python


I want to change the icon of a .lnk file after I have created it. This is my main code so far:

import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("shortcut.lnk")
shortcut.Targetpath = "C:\\Users\Benjie\AppData\Local\Programs\Python\Python36\python.exe"
shortcut.save()

This creates a shortcut with the python icon, but I want to change it to a different icon, if possible, to the icon of a different .exe file. How can I do this?

I'd preferably use one of the windows api librarys, but if this is not possible, an external library would work aswell.

Thanks


Solution

  • Ok, after a few hours of researching stuff with the help of this, I managed to find what I was looking for: shortcut.IconLocation. This sets the icon of a shortcut to an icon from an .exe, .dll .icl or .ico file. For example:

    import win32com.client
    
    shell = win32com.client.Dispatch("WScript.Shell")
    shortcut = shell.CreateShortcut("shortcut.lnk")
    shortcut.TargetPath = "C:\\Users\Benjie\AppData\Local\Programs\Python\Python36\python.exe"
    shortcut.IconLocation = "C:\path_to_.exe,1"
    shortcut.Save()
    

    The icon path is a path to the file, with a comma and the number of the icon in the file. You can see the icons for a file if you create a shortcut and change its icon in its properties, Then browse for the file.