我有用项目填充 ImageList 和 ListView 的代码:
void InsertItemsListView(HWND hwndListView, ConnectionsInfo& ci) {
int i;
LVITEM item;
ZeroMemory(&item, sizeof(item));
ListView_DeleteAllItems(hwndListView);
HIMAGELIST hSmall = CreateImageList();
for (auto it = ci.begin(); it != ci.end(); it++) {
#if 1
if (ImageList_AddIcon(hSmall, it->icon) == -1) {
continue;
}
DestroyIcon(it->icon);
it->icon = NULL;
#endif
}
ListView_SetImageList(hwndListView, hSmall, LVSIL_SMALL);
item.pszText = LPSTR_TEXTCALLBACK;
item.mask = LVIF_TEXT | LVIF_STATE | LVIF_IMAGE;
item.state = 0;
item.stateMask = 0;
item.iSubItem = 0;
for (i = 0; i < ci.size(); i++) {
item.iItem = i;
item.iImage = i;
if (ListView_InsertItem(hwndListView, &item) == -1) {
return;
}
}
}
CreateImageList()
只是一个包装:
static HIMAGELIST CreateImageList() {
InitCommonControls();
HIMAGELIST hSmall;
hSmall = ImageList_Create(
GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON),
ILC_COLOR, 1, 1);
return hSmall;
}
几乎所有内容都来自官方MSDN。我在其他论坛上看到过相同的代码,但我是唯一遇到麻烦的人:没有显示图标,但它们在内存中并且加载时没有错误:
HICON ConnectionsInfo::get_process_icon(LPCWSTR lpszFile) {
HICON icon;
UINT res = ExtractIconEx(lpszFile, 0, &icon, NULL, 1);
if (res == UINT_MAX) {
auto l = GetLastError();
HICON hi = LoadIcon(NULL, MAKEINTRESOURCE(IDI_APPLICATION));
return hi;
}
return icon;
}
虽然据说
LoadIcon()
不适用于小图标,但它仍然在MSDN的示例中。 LoadImage()
对我来说也不起作用,报告错误 1813 和 1814。ExtractIconEx()
对我来说效果很好。
我成功了!不知道为什么,但在我创建 ListView 时删除 LVS_OWNERDATA 标志后它就起作用了
dwStyle = WS_TABSTOP | WS_CHILD | WS_BORDER | WS_VISIBLE | LVS_AUTOARRANGE | LVS_REPORT | LVS_OWNERDATA;