目前只做了windows版本,用法类似QFileIconProvider
// 头文件
#ifndef WXFILEICONPROVIDER_H
#define WXFILEICONPROVIDER_H
#include <wx/wx.h>
#include <wx/icon.h>
#include <wx/image.h>
#include <wx/bmpcbox.h> // Include for wxBitmapBundle
class wxFileIconProvider : public wxObject
{
public:
wxFileIconProvider();
virtual ~wxFileIconProvider();
// Get icon for the given path
virtual wxBitmapBundle GetIcon(const wxString& path);
};
#endif
#include "wxFileIconProvider.h"
#include <wx/filename.h>
#ifdef __WXMSW__
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <wx/msw/private.h>
#include <wx/bitmap.h>
#include <wx/image.h>
#include <wx/bmpcbox.h>
wxBitmapBundle wxFileIconProvider::GetIcon(const wxString &path)
{
wxBitmapBundle bundle;
SHFILEINFO shFileInfo;
wxFileName fileName(path);
if (!fileName.Exists())
{
wxLogMessage("Error: File does not exist or is not accessible: %s", path);
return bundle;
}
wxString absolutePath = fileName.GetFullPath();
DWORD_PTR result = SHGetFileInfo(absolutePath.wc_str(), 0, &shFileInfo, sizeof(shFileInfo), SHGFI_ICON | SHGFI_SMALLICON | SHGFI_LARGEICON);
if (result)
{
if (shFileInfo.hIcon)
{
wxIcon smallIcon;
smallIcon.CreateFromHICON(shFileInfo.hIcon);
// Extract Large Icon
SHFILEINFO largeFileInfo = shFileInfo;
largeFileInfo.iIcon = 0;
SHGetFileInfo(absolutePath.wc_str(), 0, &largeFileInfo, sizeof(largeFileInfo), SHGFI_ICON | SHGFI_LARGEICON);
wxIcon largeIcon;
largeIcon.CreateFromHICON(largeFileInfo.hIcon);
if (smallIcon.IsOk() && largeIcon.IsOk())
{
wxBitmap smallBitmap = wxBitmap(smallIcon);
wxBitmap largeBitmap = wxBitmap(largeIcon);
bundle = wxBitmapBundle::FromBitmaps(smallBitmap, largeBitmap);
DestroyIcon(shFileInfo.hIcon);
DestroyIcon(largeFileInfo.hIcon);
}
else
{
DestroyIcon(shFileInfo.hIcon);
DestroyIcon(largeFileInfo.hIcon);
}
}
else
{
DestroyIcon(shFileInfo.hIcon);
}
}
else
{
DWORD error = GetLastError();
wxLogMessage("SHGetFileInfo failed with error code: %lu", error);
}
return bundle;
}
#endif
wxFileIconProvider::wxFileIconProvider() {}
wxFileIconProvider::~wxFileIconProvider() {}
// 用法
wxSize iconSize = wxSize(42, 42);
wxFileIconProvider iconProvider;
wxString filePath = "c:/users/xxx/"; // 传入文件夹或文件的路径
wxBitmapBundle bundle = iconProvider.GetIcon(filePath);
wxBitmapButton *btTest = new wxBitmapButton(this, wxID_ANY, bundle.GetBitmap(iconSize),
wxDefaultPosition, buttonSize);
传入路径,出现的就是为文件夹图标,传入文件,则是文件类型相对应的图标。