windows 如何从mime类型中获取系统文件图标?

f4t66c6m  于 6个月前  发布在  Windows
关注(0)|答案(1)|浏览(78)

我正在使用Windows应用程序,接收电子邮件.虽然这,我想在下载它们之前显示附件的图标.在那一刻,我有一个MimeType.
有没有办法只从MimeType中获取系统图标?
下载附件后,我可以使用SHGetFileInfo,但我想在下载之前有图标。

o7jaxewo

o7jaxewo1#

是的,您可以检索特定文件类型(由MIME类型确定)的系统图标,而无需实际将文件存储在磁盘上。要在Windows上实现此目的,您可以使用SHGetFileInfo函数沿着SHGFI_USEFILEATTRIBUTES标志。
下面是一个简单的C++例子:

#include <Windows.h>
#include <ShlObj.h>

HICON GetIconForMimeType(const wchar_t* mimeType) {
    SHFILEINFO sfi;
    memset(&sfi, 0, sizeof(sfi));

    // Use the SHGFI_USEFILEATTRIBUTES flag to specify that we are providing a file type (MIME type)
    SHGetFileInfo(mimeType, FILE_ATTRIBUTE_NORMAL, &sfi, sizeof(sfi), SHGFI_ICON | SHGFI_USEFILEATTRIBUTES);

    // Check if the function succeeded in getting the icon
    if (sfi.hIcon)
        return sfi.hIcon;

    // Return a default icon if the function fails
    return LoadIcon(nullptr, IDI_APPLICATION);
}

int main() {
    // Example: Get icon for a JPEG image (change the MIME type accordingly)
    const wchar_t* mimeType = L"image/jpeg";
    HICON icon = GetIconForMimeType(mimeType);

    // Now you can use the 'icon' handle as needed (e.g., display it in your application)
    // ...

    // Don't forget to clean up the icon handle when you're done with it
    DestroyIcon(icon);

    return 0;
}

字符串
image/jpeg替换为附件的MIME类型。此代码检索与指定文件类型关联的图标,而无需磁盘上的实际文件。
确保包含必要的头文件(Windows.hShlObj.h)并链接到所需的库。
请记住在应用程序中适当地处理错误和边缘情况。

相关问题