我正在尝试在 MFC 对话框上设置工具提示。我有从字符串资源读取工具提示的代码,并试图将其修改为不从资源中读取,而是组成一个工具提示。
我的实现导致垃圾显示为工具提示,而不是我想要的字符串。此外,从调试器运行时会导致崩溃,但在直接运行可执行文件时不会导致崩溃(我确信存在缓冲区损坏或类似情况)
这是相关的代码:
BOOL CPreviewDlg::OnToolTipText(UINT, NMHDR* pNMHDR, LRESULT* pResult)
{
ASSERT(pNMHDR->code == TTN_NEEDTEXT);
TOOLTIPTEXT* pTTT = (TOOLTIPTEXT*)pNMHDR;
if (!(pTTT->uFlags & TTF_IDISHWND))
return FALSE;
UINT_PTR hWnd = pNMHDR->idFrom;
// idFrom is actually the HWND of the tool
UINT nID = (UINT)(WORD)::GetDlgCtrlID((HWND)hWnd);
CString sDlgItemText;
(UINT)(WORD)::GetDlgItemText(this->GetSafeHwnd(), nID, sDlgItemText.GetBufferSetLength(50), 50);
sDlgItemText.ReleaseBuffer();
if(sDlgItemText.IsEmpty())
sDlgItemText = _T("Unnamed");
CString sToolTip = _T("");
sToolTip.Format(_T("%s \n This is the %s control. Here we can put its description."), sDlgItemText, sDlgItemText);
pTTT->lpszText = sToolTip.GetBufferSetLength(sToolTip.GetLength());/* MAKEINTRESOURCE(nID);*/
pTTT->hinst = AfxGetInstanceHandle();
sToolTip.ReleaseBuffer();
*pResult = 0;
// bring the tooltip window above other popup windows
::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, 0, 0, 0, 0,
SWP_NOACTIVATE|SWP_NOSIZE|SWP_NOMOVE|SWP_NOOWNERZORDER);
return TRUE; // message was handled
}
我很确定错误是我试图设置的地方pTTT->lpszText
(而不是 MAKEINTRESOURCE)我认为我没有得到从 CString 设置 LPSTR 的正确方法
CString sDlgItemText;
(UINT)(WORD)::GetDlgItemText(this->GetSafeHwnd(), nID, sDlgItemText.GetBufferSetLength(50), 50);
sDlgItemText.ReleaseBuffer();
if(sDlgItemText.IsEmpty())
sDlgItemText = _T("Unnamed");
CString sToolTip = _T("");
sToolTip.Format(_T("%s \n This is the %s control. Here we can put its description."), sDlgItemText, sDlgItemText);
pTTT->lpszText = sToolTip.GetBufferSetLength(sToolTip.GetLength());/* MAKEINTRESOURCE(nID);*/