从外部应用程序获取图标

2024-04-16 18:49:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在准备一个类似于“Windows开始菜单搜索”的应用程序。你知道吗

这就是为什么我需要每个应用程序都有自己的图标。你知道吗

C:\ProgramData\Start Menu\Programs\文件路径,我将现有应用程序添加到一个(QListWidget)列表中,其中包含它们的名称和路径。你知道吗

我得到这样的图标: https://forum.qt.io/topic/62866/getting-icon-from-external-applications

provider = QFileIconProvider()
info = QFileInfo("program_path")
icon = QIcon(provider.icon(info))

结果自然是: IMAGE 1

但我不想这个“快捷图标”出现。你知道吗

enter image description here

然后,我在想,我得出了这样的结论:

shell = win32com.client.Dispatch("WScript.Shell")
provider = QFileIconProvider()
shortcut = shell.CreateShortCut(programPath)
info = QFileInfo(shortcut.targetPath)
icon = QIcon(provider.icon(info))

这个解决方案奏效了。但是,这给一些应用程序带来了问题。 因此,我正在寻找一个替代解决方案。


Tags: 路径info应用程序windows解决方案shellprovidershortcut
1条回答
网友
1楼 · 发布于 2024-04-16 18:49:37

你差点就到了。你知道吗

浏览菜单目录树实际上是正确的路径,但是您还必须确保链接的图标实际上与目标相同,因为它可能不是。
shortcut.iconlocation是一个字符串,表示一个“元组”(排序),包括图标路径和索引(因为图标资源可能包含多个图标)。你知道吗

>>> shortcut = shell.createShortCut(linkPath)
>>> print(shortcut.iconlocation)
# most links will return this:
> ",0"
# some might return this:
> ",4"
# or this:
> "C:\SomePath\SomeProgram\SomeExe.exe,5"

只要图标索引为0,就可以使用QFileIconProvider和targetPathiconLocation(如果逗号前有内容)获取图标。你知道吗

当图标索引的值不同于0时,问题就出现了,因为Qt不能处理这个问题。你知道吗

我编写了一个简单的函数(基于一些研究hereonStackOverflow)。你知道吗

def getIcon(self, shortcut):
    iconPath, iconId = shortcut.iconLocation.split(',')
    iconId = int(iconId)
    if not iconPath:
        iconPath = shortcut.targetPath
    iconPath = os.path.expandvars(iconPath)
    if not iconId:
        return QICon(self.iconProvider.icon(QFileInfo(iconPath)))

    iconRes = win32gui.ExtractIconEx(iconPath, iconId)
    hdc = win32ui.CreateDCFromHandle(win32gui.GetDC(0))
    hbmp = win32ui.CreateBitmap()
    # I think there's a way to find available icon sizes, I'll leave it up to you
    hbmp.CreateCompatibleBitmap(hdc, 32, 32)
    hdc = hdc.CreateCompatibleDC()
    hdc.SelectObject(hbmp)
    hdc.DrawIcon((0, 0), iconRes[0][0])
    hdc.DeleteDC()
    # the original QtGui.QPixmap.fromWinHBITMAP is now part of the
    # QtWin sub-module
    return QtGui.QIcon(QtWin.fromWinHBITMAP(hbmp.GetHandle(), 2))

相关问题 更多 >