//ListBox数据结构体
struct ListBoxItemData {
int iconIndex; //图标索引
LPWSTR text; //文本内容
};
case WM_INITDIALOG: {// 初始化对话框
//新建ListBox
HWND hwndListBox = CreateWindowEx(0, WC_LISTBOX, L"",WS_VISIBLE | WS_CHILD | WS_VSCROLL | WS_BORDER | WS_TABSTOP | LBS_NOTIFY | LBS_OWNERDRAWFIXED ,20, 80, 160, 160, hDlg, HMENU(1809), GetModuleHandle(nullptr), nullptr); //添加自绘风格LBS_OWNERDRAWFIXED
//添加数据
ListBoxItemData* itemData1 = new ListBoxItemData;
itemData1->iconIndex = 0;
itemData1->text = (LPWSTR)L"数据1";
ListBox_InsertItemData(hwndListBox, 0, (LPARAM)(itemData1));
ListBoxItemData* itemData2 = new ListBoxItemData;
itemData2->iconIndex = 1;
itemData2->text = (LPWSTR)L"数据2";
ListBox_InsertItemData(hwndListBox, 1, (LPARAM)(itemData2));
ListBoxItemData* itemData3 = new ListBoxItemData;
itemData3->iconIndex = 2;
itemData3->text = (LPWSTR)L"数据3比较长";
ListBox_InsertItemData(hwndListBox, 2, (LPARAM)(itemData3));
break;
}
case WM_MEASUREITEM: { //设置每项的宽高
LPMEASUREITEMSTRUCT m = (LPMEASUREITEMSTRUCT)lParam;
if (m->CtlType == ODT_LISTBOX) {
m->itemHeight = 30;
}
break;
}
case WM_DRAWITEM: { //绘制每个项目
LPDRAWITEMSTRUCT d = (LPDRAWITEMSTRUCT)lParam;
if (d->CtlType == ODT_LISTBOX) { //CtlType 表示自绘控件类型
HWND hListBox = GetDlgItem(hDlg, 1809);
ListBoxItemData* itemData;
int index = d->itemID; //itemID表示项目索引
itemData=(ListBoxItemData*)ListBox_GetItemData(hListBox, index);
if (d->itemState & ODS_SELECTED) { //未被选择
DrawListBoxItem(d, RGB(255, 0, 150), RGB(160, 32, 240), itemData->text,itemData->iconIndex);
}
else { //被选择
if (d->itemID % 2 == 0) //单数行
DrawListBoxItem(d, RGB(255, 165, 0), RGB(160, 32, 240), itemData->text, itemData->iconIndex);
else //双数行
DrawListBoxItem(d, RGB(255, 0, 255), RGB(160, 32, 240), itemData->text, itemData->iconIndex);
}
}
break;
}
//绘制每个项目,包括图标和内容
void DrawListBoxItem(LPDRAWITEMSTRUCT d, COLORREF bg, COLORREF text, TCHAR* title,int icoIndex)
{
//bg 背景色
//text 文本颜色
// title 文本内容
// icoIndex图标索引
//d->hDC 绘图设备
//d->hDC 绘图设备
//d->rcItem 每个项目区域
//iMageList 添加了三章图片的HIMAGELIST
//绘制背景
HBRUSH hb = CreateSolidBrush(bg);
HBRUSH hbo = (HBRUSH)SelectObject(d->hDC, hb);
HPEN hp = CreatePen(PS_SOLID, 10, bg);
SelectObject(d->hDC, hp);
FillRect(d->hDC, &d->rcItem, hb);
SelectObject(d->hDC, hbo);
DeleteObject(hb);
//绘制文字
SetBkMode(d->hDC, TRANSPARENT);
SetTextColor(d->hDC, text);
DrawText(d->hDC, title, wcslen(title), &d->rcItem, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
//绘制图片
ImageList_Draw(iMageList, icoIndex, d->hDC, d->rcItem.left+5, d->rcItem.top+5, ILD_TRANSPARENT);
}
效果如图所示: