TVITEM LPARAM to store string

给你一囗甜甜゛ 提交于 2019-12-13 04:07:02

问题


I've got a treeview listing files that are dropped upon it.

When I make a new treeview item, I'd like to store the address of the file as a string in that item, and retrieve it for various nefarious purposes at a later point in time.

Looking at the TVITEM structure in Microsoft docs, apparently LPARAM is the place to store a value:

lParam

Type: LPARAM

A value to associate with the item.

So, I have gone ahead and done that:

TVITEM tvi;
tvi.mask = TVIF_TEXT;
tvi.pszText = const_cast<char *> (str0.c_str());
tvi.cchTextMax = sizeof(tvi.pszText);
tvi.lParam = (LPARAM) foo;  // SETTING LPARAM HERE, foo IS A const char * 

TVINSERTSTRUCT tvis;
tvis.item = tvi;
tvis.hInsertAfter = 0;
tvis.hParent = hti0;

// Send message to update tree, and return tree item.
return TreeView_InsertItem(tvw_filelist_, &tvis);

Then, when I try to retrieve my value...

HTREEITEM htiSel = TreeView_GetSelection(tvw_filelist_);

TVITEM tvItem;
tvItem.hItem = htiSel;

TreeView_GetItem(tvw_filelist_, &tvItem);
const char * info = (const char *) tvItem.lParam;
MessageBox(NULL, info, "Alert", MB_OK);

...I just get garbage, indicating my pointer went out of scope or is taking a nap or something. The size of that pointer is always 4.

Is this the right way to do what I'm trying to do? If so, what's going on?


回答1:


Of course, take the time to post a question after a long time trying to figure it out, and the answer shows up in seconds.

Turns out the TVITEM mask needs to include TVIF_PARAM, similar to this question.

If I change the above code to:

tvi.mask = TVIF_TEXT | TVIF_PARAM;

it works as expected.

I'm still not sure if this is the recommended use for LPARAM, though.




回答2:


struct CustomTreeData
{
    LPSTR str;   // or even std::string to forget about memory managment
    // TODO: any other data you need
};
...
TVITEM tvi;
tvi.mask = TVIF_TEXT | TVIF_PARAM;

CustomTreeData* myDataPtr = new CustomTreeData;   // the memory should be free later
myDataPtr->str = stringWhatIWant;   // And don't forget to alloc memory for str!
tvi.lParam = (LPARAM) myDataPtr;

I don't check this code, but it should work. Happy coding :)



来源:https://stackoverflow.com/questions/13285126/tvitem-lparam-to-store-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!