c++winapilistboxownerdrawn

Owner draw listbox alway return (LPDRAWITEMSTRUCT)->itemID = -1


I created an owner draw listbox. Do you know why in WM_DRAWITEM message, I only receive (LPDRAWITEMSTRUCT)lParam->itemID = -1?

I'm coding with VS 2010 C++ Express and Win 7.

Create listbox and set scroll info:

lbHWND = CreateWindowExW(NULL, WC_LISTBOX, NULL,
    WS_CHILD | WS_BORDER | WS_VISIBLE | LBS_NODATA | 
    LBS_OWNERDRAWFIXED | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT,
    0, 0, 400, 400, tkHWND, (HMENU)IDC_LISTBOX_ENTRY, hInstance, 0);

SCROLLINFO lbSi = { 0 };
lbSi.cbSize = sizeof(SCROLLINFO);
lbSi.fMask = SIF_RANGE | SIF_PAGE | SIF_POS;
lbSi.nMin = 0;
lbSi.nMax = 1000;
lbSi.nPage = 20;
lbSi.nPos = 0;
SetScrollInfo(lbHWND, SB_VERT, &lbSi, TRUE);

WinProc:

LRESULT CALLBACK WndProc(HWND phwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
        case WM_MEASUREITEM:
        {
            MEASUREITEMSTRUCT*  lpmis = (LPMEASUREITEMSTRUCT)lParam;
            switch (lpmis->CtlID)
            {
                case IDC_LISTBOX_ENTRY:
                    lpmis->itemHeight = 20;
                    break;
                default:
                    break;
            }
            return TRUE;
        }
        case WM_DRAWITEM:
        {
            DRAWITEMSTRUCT* lpdis = (LPDRAWITEMSTRUCT)lParam;

            // Check lpdis->itemID, for test purpose only
            FILE *f;
            if (!_wfopen_s(&f, L"E:\\lb.txt", L"ab"))
            {
                fprintf(f,"%d\r\n", lpdis->itemID);
                fclose(f);
            }
            // lpdis->itemID always = -1
            return TRUE;
        }
    }
}

Solution

  • I have find the answer: For an owner draw listbox with LBS_NODATA style, I have to tell the listbox number of items it has.

    SendMessage(lbHWND, LB_RESETCONTENT, 0, 0);    // Remove all items, if have any
    SendMessage(lbHWND, LB_SETCOUNT, 1000, 0);     // Set number of items (here is 1000)