做GUI时经常需要让控件或者控件的每个Item附带一些数据.ListCtrl和TreeCtrl等复杂的控件都有类似于SetItem之类的API函数可以附加自己的数据.对于窗口句柄HWND,也有类似的函数,就是SetProp、GetProp等API。具体使用MSDN有详细的介绍和例子。下面我为方便使用而对其进行简要地封装.
#ifndef _WINDOW_PROP_H_
#define
_WINDOW_PROP_H_
/*
* 封装API函数SetProp、GetProp、EnumPropsEx、RemoveProp
* 用于管理窗口的属性
*/
class
CWindowProp
{
private
:
//
保存需要设置的窗口句柄
HWND m_hWnd;
public
:
CWindowProp( HWND hWnd
=
NULL )
{
this
->
m_hWnd
=
hWnd;
}
CWindowProp
&
operator
=
( HWND hWnd )
{
this
->
m_hWnd
=
hWnd;
return
*
this
;
}
/*
* 设置属性值
* lpszName: 属性key
* hData: 值句柄
* Return: 返回成功与否
*/
BOOL SetProperty( LPCTSTR lpszName, HANDLE hData )
{
ATLASSERT( ::IsWindow(
this
->
m_hWnd ) );
return
::SetProp(
this
->
m_hWnd, lpszName, hData );
}
/*
* 获取属性值
* lpszName: 属性key
* Return: lpszName对应的值,若不存在返回NULL
*/
HANDLE GetProperty( LPCTSTR lpszName )
{
ATLASSERT( ::IsWindow(
this
->
m_hWnd ) );
return
::GetProp(
this
->
m_hWnd, lpszName );
}
/*
* 删除属性值
* lpszName: 属性key
* Return: lpszName对应的值,若不存在返回NULL
*/
HANDLE RemoveProperty( LPCTSTR lpszName )
{
ATLASSERT( ::IsWindow(
this
->
m_hWnd ) );
return
::RemoveProp(
this
->
m_hWnd, lpszName );
}
/*
* 枚举属性列表
*/
BOOL EnumerateProperties( PROPENUMPROCEX pfnProc, LPARAM lParam)
{
ATLASSERT( ::IsWindow(
this
->
m_hWnd ) );
ATLASSERT(
!
::IsBadCodePtr( (FARPROC)pfnProc ) );
return
::EnumPropsEx(
this
->
m_hWnd, pfnProc, lParam)
!=
-
1
;
}
/*
* 删除所有的属性列表
*/
void
RemoveAll()
{
ATLASSERT( ::IsWindow(
this
->
m_hWnd ) );
::EnumPropsEx(
this
->
m_hWnd, sRemoveAllProc,
0
);
}
private
:
static
BOOL CALLBACK sRemoveAllProc( HWND hWnd, LPTSTR lpszName, HANDLE hData, ULONG_PTR dwData )
{
::RemoveProp( hWnd, lpszName );
return
TRUE;
}
};
#endif