Win32 realizes ListBox self-drawing

My WeChat public account : CPP Advanced Tour
If you think this article is helpful to you, please pay attention to "CPP Advanced Tour" to learn more technical dry goods

1. The main points of the ListBox control self-drawing

  1. When creating a window in CreateWindowEx, you need to set the two properties of LBS_OWNERDRAWFIXED | LBS_HASSTRINGS to the parameter dwStyle. And you need to process the WM_DRAWITEM and WM_MEASUREITEM messages in the parent window of the listbox window to redraw the list box.
  2. LBS_OWNERDRAWFIXED: Specifies that the parent window of the list box is responsible for drawing its content, and the items in the list box have the same height. When the list box is created, the parent window will receive the WM_MEASUREITEM message; if the appearance of the list box has changed, the parent window will receive the WM_DRAWITEM message.
    You can also replace LBS_OWNERDRAWFIXED with LBS_OWNERDRAWVARIABLE as needed. LBS_OWNERDRAWVARIABLE specifies that the parent window that is also used for the list box is responsible for drawing its content, and the height of the items in the list box is variable.
  3. LBS_HASSTRINGS: If LBS_HASSTRINGS is not set, the string obtained through the LB_GETTEXT message or ListBox_GetText method will be garbled

2, ListBox control self-drawing key code

//创建listbox
HWND	hwndListBox =CreateWindowEx(0, WC_LISTBOX, L"",
WS_VISIBLE | WS_CHILD | WS_VSCROLL | WS_BORDER | WS_TABSTOP | LBS_NOTIFY | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS,//如果不设定LBS_HASSTRINGS,那么GetText取得的将是乱码
20, 20, 360, 240, hWnd, nullptr,GetModuleHandle(nullptr), nullptr);

//添加数据
for (int i = 0; i < 10; i++) {
	WCHAR itemText[256];
	ZeroMemory(itemText, sizeof(itemText));
	wsprintf(itemText, L"item %d", i);
	ListBox_AddString(hwndListBox, itemText);
}


//在父窗口中处理WM_DRAWITEM消息实现列表条目的自绘
case WM_DRAWITEM:
	{
		DRAWITEMSTRUCT* pdis = (DRAWITEMSTRUCT*)lParam;
		if (pdis->itemAction != ODA_DRAWENTIRE && pdis->itemAction != ODA_SELECT)
			break;
		LPDRAWITEMSTRUCT pDI = (LPDRAWITEMSTRUCT)lParam;
		HBRUSH brsh = CreateSolidBrush(RGB(255 - 30 * pDI->itemID, 128 + 40 * pDI->itemID, 128 + 40 * pDI->itemID));//yellow  
		FillRect(pDI->hDC, &pDI->rcItem, brsh);
		DeleteObject(brsh);
		// text   
		SetBkMode(pDI->hDC, TRANSPARENT);
		WCHAR szText[260];
		SendMessage(hwndListBox, LB_GETTEXT, pDI->itemID, (LPARAM)szText);
		const DWORD dwStyle = DT_LEFT | DT_SINGLELINE | DT_VCENTER | DT_NOPREFIX | DT_END_ELLIPSIS;
		DrawText(pDI->hDC, szText, wcslen(szText), &pDI->rcItem, dwStyle);
	} break;

3. Complete code

https://download.csdn.net/download/siyacaodeai/15452147

4. Important note

Welcome everyone to follow my personal WeChat public account to view professional client/server development knowledge, written test interview questions, programmers’ workplace experience and experience sharing.
Insert picture description here

Guess you like

Origin blog.csdn.net/siyacaodeai/article/details/114037834