①、声明 CToolTipCtrl 类型对象:
CToolTipCtrl m_pToolTipCtrl;
===================================================
②、CToolTipCtrl 的创建:
if( !m_pToolTipCtrl.Create(this) ) return FALSE;
===================================================
③、添加需要提示的控件:
CString strTip = _T("C:\\Documents and Settings\\Syc\\Application Data\\Microsoft\\Internet Explorer\\Quick Launch\\");
m_pToolTipCtrl.AddTool(GetDlgItem(IDC_EDIT), strTip);
SetDlgItemText(IDC_EDIT, strTip);
===================================================
④、添加虚函数 PreTranslateMessage
BOOL CDlgTestDlg::PreTranslateMessage(MSG* pMsg)
{
if(pMsg->message == WM_LBUTTONDOWN ||
pMsg->message == WM_LBUTTONUP ||
pMsg->message == WM_MOUSEMOVE)
m_pToolTipCtrl.RelayEvent(pMsg); //传递一个鼠标消息给工具提示控件处理
return CDialog::PreTranslateMessage(pMsg);
}
===================================================
⑤、为控件添加动态提示内容:
前三步不变,在调用 AddTool 增加 ToolTip 时不指定显示的字串,而是使用 LPSTR_TEXTCALLBACK 参数;
并启用目标窗口的 ToolTip 属性:EnableToolTips(TRUE);
===================================================
⑥、增加消息映射:
afx_msg BOOL OnTtnNeedText(UINT id, NMHDR *pNMHDR, LRESULT *pResult);
ON_NOTIFY_EX(TTN_NEEDTEXT, 0, &CDlgTestDlg::OnTtnNeedText)
===================================================
⑦、添加 OnTtnNeedText 函数实现:
BOOL CDlgTestDlg::OnTtnNeedText(UINT id, NMHDR *pNMHDR, LRESULT *pResult)
{
UNREFERENCED_PARAMETER(id);
TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *)pNMHDR;
UINT_PTR nID = pNMHDR->idFrom; //获得目标窗口ID,有可能是HWND
BOOL bRet = FALSE;
if (pTTT->uFlags & TTF_IDISHWND) { //表明nID是否为HWND
bRet = TRUE;
CString strText;
// idFrom is actually the HWND of the tool
nID = ::GetDlgCtrlID((HWND)nID); //从HWND得到ID值,当然你也可以通过HWND值来判断
switch (nID)
{
case IDC_EDIT:
case IDC_BTN:
strText.Empty();
GetDlgItemText(nID, strText);
pTTT->lpszText = (LPTSTR)(LPCTSTR)strText;
pTTT->hinst = AfxGetResourceHandle();
default:break;
}
}
*pResult = 0;
return bRet;
} |