所有者总是绘制列表框 return (LPDRAWITEMSTRUCT)->itemID = -1

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

我创建了一个所有者绘制的列表框。你知道为什么在WM_DRAWITEM消息中,我只收到(LPDRAWITEMSTRUCT)lParam->itemID = -1吗?

我正在使用 VS 2010 C++ Express 和 Win 7 进行编码。

创建列表框并设置滚动信息:

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;
        }
    }
}

我找到了答案:对于具有 LBS_NODATA 样式的所有者绘制列表框,我必须告诉列表框它拥有的项目数。

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)