ST本身具备显示Tooltip的功能,但是限于在exe程序中,要是在dll或者ocx等程序中,则Tooltip显示不出来,问题在于对于dll中的资源来说,根本无法响应pretranslatemessage 函数 ,所以tooltips显示不出来。网上给出了两个办法解决:1 消息钩子;2 dll 导出函数;
个人觉得都太麻烦,于是修改了CButtonST类,将其成员m_Tooltip类型从MFC的CTooltipCtrl改为自己实现的CTipWnd(继承自CStatic),一劳永逸的解决了在dll工程中使用CButtonST显示不了Tooltip的问题。修改后的CButtonST可直接拿来使用,并显示Tooltip。
下面给出源码和关键代码:
//目的:解决CBUTTONST有关“SetTooltipText”无效的问题。 //目的:解决了提示框显示位置超范围和显示位置不合适的问题。 void CButtonST::ShowTooltip(BOOL bShow) { if(m_ToolTip.GetSafeHwnd() == NULL) return; if(bShow) { if(m_ToolTip.IsShow()) return; m_ToolTip.SetShowFlag(TRUE); //目的:获取提示框的默认显示位置。 CRect rc; m_ToolTip.GetWindowRect(&rc); ClientToScreen(&rc); CRect rect; GetClientRect(&rect); ClientToScreen(&rect); rc.OffsetRect(rect.left - rc.left, rect.bottom - rc.top + 10); /* //目的:测试提示框的位置。 rc.top = rc.top - 50; rc.bottom = rc.bottom - 50; rc.left = rc.left - 50; rc.right = rc.right - 50;*/ //对话框窗体大小及其屏幕坐标 //目的:获取主窗体的大小。Add by 石民生 2018.06.04 CRect rectDlg; CWnd* pWnd = AfxGetMainWnd(); pWnd->GetWindowRect(rectDlg);//获得窗体在屏幕上的位置 //目的:提示框的默认显示位置上移5px。 rc.top = rc.top - 5; rc.bottom = rc.bottom - 5; if (rc.top < 0) { rc.OffsetRect(0, 0 - rc.top); } if (rc.left < 0) { rc.OffsetRect(0 - rc.left, 0); } //目的:提示框的最右端不能超出窗体的右端位置。 if (rc.right > (rectDlg.left + rectDlg.right)) { int offsetPx = rc.right - (rectDlg.left + rectDlg.right); rc.left = rc.left - offsetPx; rc.right = rc.right - offsetPx; } //目的:提示框的最底端不能超出窗体的底边。 if (rc.bottom > (rectDlg.top + rectDlg.bottom)) { int offsetPy = rc.bottom - (rectDlg.top + rectDlg.bottom); rc.top = rc.top - offsetPy; rc.bottom = rc.bottom - offsetPy; } m_ToolTip.MoveWindow(&rc); m_ToolTip.ShowWindow(SW_SHOW); } else { m_ToolTip.ShowWindow(SW_HIDE); m_ToolTip.SetShowFlag(FALSE); } }
函数定义如下:
CTipWnd m_ToolTip; // Tooltip
void SetTooltipText(LPCTSTR lpszText, BOOL bActivate = TRUE);
// This function sets the text to show in the button tooltip. // // Parameters: // [IN] lpszText // Pointer to a null-terminated string containing the text to show. // [IN] bActivate // If TRUE the tooltip will be created active. // void CButtonST::SetTooltipText(LPCTSTR lpszText, BOOL bActivate) { // We cannot accept NULL pointer if (lpszText == NULL) return; // Initialize ToolTip if (m_ToolTip.GetSafeHwnd() == NULL) m_ToolTip.Create(); m_ToolTip.SetTipText(CString(lpszText)); } // End of SetTooltipText
设置文本内容提示的实现:
void CTipWnd::SetTipText(CString strTipText) { m_strTipText = strTipText; m_uBGImageID = IDB_TOOLTIP_BG; //根据TooltipText设置窗口大小 CDC* pDC = GetDC(); pDC->SelectObject(&m_oFont); CSize size = pDC->GetTextExtent(m_strTipText); CRect rect(0, 0, size.cx + 10, size.cy + 10); MoveWindow(&rect); }
源码下载: