使用CToolTipCtrl进行自定义控制的工具提示? (MFC)

时间:2010-04-26 09:14:25

标签: c++ mfc

我制作了一个源自CWnd的自定义控件(折线图),我想知道我是否可以使用CToolTipCtrl显示图表上点的工具提示。如果是的话,我怎么能这样做?

顺便说一句,当我将鼠标移到该点上时,应该弹出包含有关该点值的信息的矩形。

1 个答案:

答案 0 :(得分:5)

是的,这是有效的,实际上我也做同样的事情,也是在折线图中,但是有一些缺点/评论。消息处理有点不稳定,根据文档没有发送一些消息,并且需要一些解决方法来保持控件自包含(不需要父级的帮助来反映通知)。

您所做的是在CWnd派生类中声明一个变量

CToolTipCtrl m_ToolTipCtrl;
CString m_ToolTipContent;

然后在OnCreate上执行此操作:

m_ToolTipCtrl.Create(this, TTS_ALWAYSTIP);
m_ToolTipCtrl.Activate(TRUE);

您也可以选择设置延迟时间:

m_ToolTipCtrl.SetDelayTime(TTDT_AUTOPOP, -1);
m_ToolTipCtrl.SetDelayTime(TTDT_INITIAL, 0);
m_ToolTipCtrl.SetDelayTime(TTDT_RESHOW, 0);

如果要显示工具提示(可能是在OnMouseMove()中),请使用

m_ToolTipCtrl.Pop();

但这仅适用于UNICODE版本。因此,如果您仍然使用MBCS(就像我一样),您只能在一定延迟后显示工具提示。 使用它来设置工具提示文本(也在OnMouseMove中):

// Not using CToolTipCtrl::AddTool() because
// it redirects the messages to the parent
TOOLINFO ti = {0};
ti.cbSize = sizeof(TOOLINFO);
ti.uFlags = TTF_IDISHWND;    // Indicate that uId is handle to a control
ti.uId = (UINT_PTR)m_hWnd;   // Handle to the control
ti.hwnd = m_hWnd;            // Handle to window
// to receive the tooltip-messages
ti.hinst = ::AfxGetInstanceHandle();
ti.lpszText = LPSTR_TEXTCALLBACK;
ti.rect = <rectangle where, when the mouse is over it, the tooltip should be shown>;
m_ToolTipCtrl.SendMessage(TTM_ADDTOOL, 0, (LPARAM) (LPTOOLINFO) &ti);
m_ToolTipCtrl.Activate(TRUE);

m_ToolTipContent = "my tooltip content";

此外,您需要处理TTNNeedText:

// The build-agnostic one doesn't work for some reason.
ON_NOTIFY_EX(TTN_NEEDTEXTA, 0, OnTTNNeedText)
ON_NOTIFY_EX(TTN_NEEDTEXTW, 0, OnTTNNeedText)

BOOL GraphCtrlOnTTNNeedText(UINT id, NMHDR* pTTTStruct,  LRESULT* pResult)
{
    TOOLTIPTEXT* pTTT = (TOOLTIPTEXT*)pTTTStruct;
    //pTTT->lpszText = "some test text";
    //pTTT->lpszText = m_ToolTipContent;
    strncpy_s(pTTT->lpszText, 80, m_ToolTipContent, _TRUNCATE);

    return TRUE;
}

您必须稍微修改一下,并阅读函数和消息的文档,以便在项目中使用它,但是可以这样做。

相关问题