How to enable tooltip for your dialog controls?

28 04 2008


Have a number of controls in your dialog. May be a single line of tooltip will add beauty to it. So how can you add tooltips for the controls in your dialog? Its easy. Just follow the steps.


Basically you’ve to enable tooltips by calling EnableToolTips() and then handle the TTN_NEEDTEXT message in your dialog. When its time to show a tooltip, windows will send you the TTN_NEEDTEXT message with control’ handle and you’ve to specify the tooltip text to be shown. From handle you can get Dialog control ID. Once you have the control ID, you can specify which tooltip have to be shown for that control. See it step by step. I assume you use MFC. Eventhough you follow the tradition style, just go through the steps, you can easily grasp it.

1) Call EnableToolTips() in yout dialog initialize function. The best place is in dialog initialization routine – CDialog::OnInitDialog().
2) Now add message handler for TTN_NEEDTEXT in messagemap. The following codesnippet enables tooltip notification for all controls in your dialog.

BEGIN_MESSAGE_MAP(CDialogDlg, CDialog)
    ...
    ON_NOTIFY_EX_RANGE(TTN_NEEDTEXT, 0, 0xFFFF, OnToolTipNotify)
END_MESSAGE_MAP()

3) Now declare the tooltip handler in your header as follows.

afx_msg BOOL OnToolTipNotify( UINT id,
                              NMHDR* pNMHDR,
                              LRESULT* pResult );

4) Now define the tooltip handler in your cpp file as follows

BOOL CDialogDlg::OnToolTipNotify( UINT id,
                                  NMHDR * pNMHDR,
                                  LRESULT * pResult )
{
    // Get the tooltip structure.
    TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *)pNMHDR;

    // Actually the idFrom holds Control's handle.
    UINT CtrlHandle = pNMHDR->idFrom;

    // Check once again that the idFrom holds handle itself.
    if (pTTT->uFlags & TTF_IDISHWND)
    {
        // Get the control's ID.
        UINT nID = ::GetDlgCtrlID( HWND( CtrlHandle ));

        // Now you have the ID. depends on control,
        // set your tooltip message.
        switch( nID )
        {
        case IDC_BUTTON1:
                // Set the tooltip text.
                pTTT->lpszText = _T("First Button");
            break;

        case IDC_BUTTON2:
            // Set the tooltip text.
            pTTT->lpszText = _T("Second Button");
            break;

        default:
            // Set the tooltip text.
            pTTT->lpszText = _T("Tooltips everywhere!!!");
            break;
        }

        return TRUE;
    }

    // Not handled.
    return FALSE;
}


Targeted Audience – Beginners.

Advertisements