I’m a beginner at programming and recently started experimenting with creating shortcuts using python.
I know how to create a shortcut using win32com client but was wondering how to copy the same icon of the target file to its shortcut that is being created.
To illustrate, here is the code:
import win32com.client
path = r"D:\\meh.lnk"
target = r"D:\\Python\words.txt"
icon = r"" # i dont have any icon to attach here yet.
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.IconLocation = icon
So I was wondering how I can set the path of the original target file’s icon to the the icon
variable, to attach it to its shortcut, or some other way to achieve the same goal.
I haven’t really tried anything yet because i dont know where to start, i did try to put the same path of the target file to the icon variable, but that did not work.
>Solution :
You can use the GetIconLocation method of the IShellLink interface to get the icon location of the target files
import win32com.client
# Create a shell link object
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(path)
# Set the target path of the shortcut
shortcut.Targetpath = target
# Get the icon location of the target file
target_icon_location = shortcut.GetIconLocation()
# Set the icon location of the shortcut to the icon location of the target file
shortcut.IconLocation = target_icon_location
This is how you can set the path of the original target file’s icon to the the icon variable