开发者

How can i attach userdata to each item in a listview? C++ Win32

I was thinking i could use the LVITEM structures LPARAM to attach a pointer to my class, but i can't seem to 开发者_如何学编程get it to work!

Heres the main parts of my code:

Creating the listview:

hlvQuiz = CreateChild(WC_LISTVIEW, "",
    WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | LVS_ICON | LVS_AUTOARRANGE,
    0, 0, 320, 240, m_hwnd, FontNormal);

Adding items:

if (vQuizes.size() > 0)
{
    LVITEM lvi;
    lvi.mask = LVIF_TEXT | LVIF_PARAM;
    lvi.iItem = 0;
    lvi.iSubItem = 0;
    lvi.cchTextMax = QUIZSTRLEN;

    for (unsigned int i = 0; i < vQuizes.size(); i++)
    {
        lvi.lParam = (LPARAM)&vQuizes[i]; // adding pointer to lparam
        lvi.pszText = vQuizes[i].szName;
        ListView_InsertItem(hlvQuiz, &lvi);
    }
}

Then later when i go to get my class back from the LPARAM:

        LVITEM lvi;
    lvi.iItem = ListView_GetNextItem(hwnd, -1, LVNI_SELECTED);
    lvi.iSubItem = 0;

    if (ListView_GetItem(fm->hlvQuiz, &lvi) == TRUE)
    {
        Quiz* q = (Quiz*)lvi.lParam;
        if (q != NULL) // i get stopped here because my pointer is NULL
            if (Exists(q->szPath) == IS_FILE)
                ShellExecute(NULL, "edit", q->szPath, NULL, NULL, SW_SHOWNORMAL);
    }

Is there anything that i'm doing wrong? the listview creates fine, and the items add, but the pointer to my class which i put in the LPARAM value seems to be ignored, or changed by the time i come to dereference it


I haven't worked at this low level before, but I suspect you need to set the mask member of the LVITEM structure to LVIF_PARAM (as well as the appropriate values for anything else you need) for the call to ListView_GetItem.


Your code works fine in Debug mode but not in Release mode because you missed to specify the name of LPARAM in lvi.mask (and the name of any other field you want back).

Try this:

lvi.iItem = ListView_GetNextItem(hlvQuiz, -1, LVNI_SELECTED);
lvi.mask = LVIF_PARAM;

if (ListView_GetItem(fm->hlvQuiz, &lvi) == TRUE) ...

You'll receive a copy of the LPARAM's value you've setted. I think that this little strange behaviour is due to the Debug mode's help that initalize everything for you. The Release mode instead do not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜