Article ID: 133257
Article Last Modified on 11/21/2006
int CMyWnd::OnCreate()
{
...
CString str("Helpful Info");
m_ToolTip.Create(this);
m_ToolTip.AddTool(this,str);
...
}
The CString object used in the call to AddTool is temporary. As soon as the
function exits, the string buffer is freed and the tooltip is pointing to
an invalid address. The overloaded version of CToolTip::AddTool, which
takes a resource ID as an argument, has this problem. This is easy to see
in the implementation of the function:
BOOL CToolTipCtrl::AddTool(CWnd* pWnd, UINT nIDText,
LPCRECT lpRectTool, UINT nIDTool)
{
ASSERT(nIDText != 0);
CString str;
VERIFY(str.LoadString(nIDText));
return AddTool(pWnd, str, lpRectTool, nIDTool);
}
// TTFIX.H
//
// CFixToolTipCtrl
//
// CToolTipCtrl-derived class that duplicates the strings
// passed in to AddTool and SetToolInfo so that they will be
// properly stored until the tooltip is destroyed.
//
class CFixToolTipCtrl : public CToolTipCtrl
{
protected:
CPtrList m_lstTips;
public:
CFixToolTipCtrl();
virtual ~CFixToolTipCtrl();
// Generated message map functions
protected:
//{{AFX_MSG(CFixToolTipCtrl)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
afx_msg LRESULT OnAddTool(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
};
// END OF TTFIX.H
/////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
// TTFIX.CPP
//
#include "stdafx.h"
#include <afxcmn.h>
#include "ttfix.h"
BEGIN_MESSAGE_MAP(CFixToolTipCtrl, CToolTipCtrl)
//{{AFX_MSG_MAP(CFixToolTipCtrl)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
ON_MESSAGE(TTM_ADDTOOL, OnAddTool)
END_MESSAGE_MAP()
CFixToolTipCtrl::~CFixToolTipCtrl()
{
while (!m_lstTips.IsEmpty())
free(m_lstTips.RemoveHead());
}
LRESULT CFixToolTipCtrl::OnAddTool(WPARAM wParam, LPARAM lParam)
{
TOOLINFO ti = *(LPTOOLINFO)lParam;
if ((ti.hinst == NULL) && (ti.lpszText != LPSTR_TEXTCALLBACK)
&& (ti.lpszText != NULL))
{
char *pStr = _tcsdup(ti.lpszText);
m_lstTips.AddTail(pStr);
ti.lpszText = pStr;
}
return DefWindowProc(TTM_ADDTOOL, wParam, (LPARAM)&ti);
}
// END OF TTFIX.CPP
Additional query words: 2.10 2.20 3.1 3.10 3.2 3.20 Incorrect Corrupted
Keywords: kbbug kbcode kbfix kbtooltip kbuidesign kbvc400fix KB133257