我如何检索ctreectrl MFC的LPARAM值 [英] How I retrieve the LPARAM value of a ctreectrl MFC

查看:118
本文介绍了我如何检索ctreectrl MFC的LPARAM值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个树控件,其中每个节点都与一个LPARAM值相关联。在特定的按钮单击事件上,我想要检索LPARAM值。下面给出的代码执行不止一次。所以,当我试图检索初始值的LPARAM值时,它是一个垃圾值。



我尝试了什么:



I have a Tree Control where each node is associated with a LPARAM value. On a particular button click event I want to retrieve the LPARAM value. The below given code is executed more than once. so when i trying to retrieve the LPARAM value for the initial values its a garbage value.

What I have tried:

strTemp.Format(_T("%s %f %s %f"), _T("Length: "), fLength, _T("-->"), fCXLength);
m_strParamval = _T("LENG") + CXString::Format(_T("%d"), m_nMatID);
LPCTSTR pszParamVal = m_strParamval;

HTREEITEM hMatChild = m_cTreeCtrl.InsertItem(TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE | TVIF_PARAM,strTemp, 0, 0, 0, 0, (LPARAM)pszParamVal, m_hMatNode, TVI_LAST);









这是检索的男女同校:







this is the coed for retrieving:

TVITEMEX item1;
item1.mask = TVIF_PARAM;
item1.hItem = m_hMatTest;


TreeView_GetItem(m_cTreeCtrl, &item1);
CString strPath1 = (LPCTSTR)item1.lParam;

推荐答案

这将永远不会按预期工作。



您将字符串存储在 m_strParamval 中。每当插入新项目时,此字符串都将更新。所以你总是得到最后添加项目的字符串。



但更重要的是, LPARAM 值可能不再指向有效的字符串了。 m_strParamval 类型为 CString ,在分配大于现有内容的新字符串时,可能会分配新内存。然后由 CString :: GetString()返回的指针(在将 CString 分配给<$ c时使用$ c> LPCTSTR )不再有效。



如果你想为每个项目存储单独的字符串,你必须使用已分配的内存删除项目并销毁树时,每个项目都可以释放。

示例:

This will never work as expected.

You are storing the string in m_strParamval. This string will be updated whenever you insert a new item. So you would always get the string for the last added item.

But more important, the LPARAM values might not point to a valid string anymore. m_strParamval is of type CString which might allocate new memory when assigning a new string that is larger than the existing content. Then the pointer returned by CString::GetString() (which is used when assigning a CString to a LPCTSTR) is not valid anymore.

If you want to store individual strings for each item you have to use allocated memory for each item and free that when items are removed and the tree is destroyed.
Example:
CString strParamval = _T("LENG") + CXString::Format(_T("%d"), m_nMatID);
TCHAR *pszParamVal = new TCHAR[strParamval.GetLength()];
_tcscpy(pszParamVal, strParamval.GetString());

再次:当这样做时,不要忘记在删除项目或破坏树控件时删除内存。

Again: When doing so, don't forget to delete the memory when deleting items or destroying the tree control.


这篇关于我如何检索ctreectrl MFC的LPARAM值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆