0319 CTreeCtrl  SetItemData GetItemData

CTreeCtrl::GetItemData
Call this function to retrieve the 32-bit application-specific value associated with the specified item.

DWORD_PTR GetItemData(
   HTREEITEM hItem
) const;
Parameters
hItem
Handle of the item whose data is to be retrieved.
Return Value
A 32-bit application-specific value associated with the item specified by hItem.

CTreeCtrl::SetItemData
This method sets the 32-bit application-specific value associated with the specified item.

BOOL SetItemData(
HTREEITEM hItem,
DWORD dwData );
Parameters
hItem
Specifies the handle of the item whose data is to be retrieved.
dwData
Specifies a 32-bit application-specific value associated with the item specified by hItem.
Return Value
Nonzero if it is successful; otherwise, it is zero.

一个很简单的应用:
pCtrl->SetItemData(hitem,1234);
DWORD d= pCtrl->GetItemData(a);

然后我就想放一个字符串:
CString  s=("sdf");;
pCtrl->SetItemData(hitem,(DWORD)&s);
 CString * d=(CString *)pCtrl->GetItemData(a);

结果:s 00384C64  31 32 33 00
- s &leftsign;"123"&rightsign;
- m_pchData 0×00384c64 "123"

- d 0×0012f578 &leftsign;"栩J_-"&rightsign;
+ m_pchData 0×00152b98 "栩J_-"

真是很奇怪,最后改成:
CString *s=new CString("123");
pCtrl->SetItemData(hitem,(DWORD)&s);

CString   *d=(CString *)pCtrl->GetItemData(a);
- s 0×00384c58 &leftsign;"123"&rightsign;
+ m_pchData 0×00384e54 "123"

- d 0×00384c58 &leftsign;"123"&rightsign;
+ m_pchData 0×00384e54 "123"

原因:
It returns a temporary instance of CString. This instance is destroyed right after you cast it to DWORD. Moreover, the result of C-style cast in this case is completely useless.

You have to store the variable somewhere.
一旦函数结束,CString对象被销毁,在其他函数里调用GetItemData返回的都是无效指针,程序多半会崩溃。

char *ss=new char[255];
         strcpy(ss,"1234");
         pCtrl->SetItemData(hitem,(DWORD)ss);

char   *d=(char *)pCtrl->GetItemData(a);
- ss 0×00384ea0 "1234"
+ d 0×00384ea0 "1234"
因为树上显示的只是一个标签信息。而我们可以用Data来记录一些详细的信息。比如树上显示一个学生的名字,而我们可以用Data来记录这个学生的学号。因为用名字是无法唯一定位是哪个学生,而学号是可以的。同时,Data的类型是DWORD类型,与指针的类型是一致的,所以也可以记录一块内存的起始地址。用GetItemData就可以获取了。

历史博文

标签:,
七月 28, 2006 at 9:41 下午 by yippee 1,043 次
Category: Dev
Tags: ,