Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copying the icon of target file to its shortcut in Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading