Create Tool Tip Using mfc ctooltipctrl
Tool-tips—those little yellow boxes that pop up with helpful text—add a touch of polish to your user interfaces. They guide users by providing context-sensitive information about buttons, text fields, and other controls. While MFC (Microsoft Foundation Classes) offers a built-in CToolTipCtrl class for tool-tips, let’s create a custom helper class to streamline their use and open up possibilities for future enhancements.
Understanding MFC Tool-Tips
Let’s refresh the basics:
- Tool: A control within your MFC dialog (e.g., a button, edit box).
- Tip: The descriptive text that appears in a yellow box when the user’s mouse hovers over the tool.
- MFC’s CToolTipCtrl: The underlying MFC class that manages tracking mouse movement and displaying the tip.
Creating Our Helper Class
- New MFC Class (CToolTipCtrlExt)
- Right-click your MFC project in Visual Studio and select “Add” -> “Class…”.
- Name it CToolTipCtrlExt and make it derive from CToolTipCtrl.
- The Display_tooltip_text Function Inside CToolTipCtrlExt.h:
- C++
- void Display_tooltip_text(LPCTSTR display_text, CWnd* pWnd);
- Implementation (CToolTipCtrlExt.cpp)
- C++
- void CToolTipCtrlExt::Display_tooltip_text(LPCTSTR display_text, CWnd* pWnd)
- {
- TOOLINFO ti;
- ti.cbSize = sizeof(TOOLINFO);
- ti.lpszText = (LPSTR)display_text;
- ti.hwnd = pWnd->GetParent()->GetSafeHwnd(); // Parent of the control
- ti.uFlags = TTF_IDISHWND | TTF_SUBCLASS;
- ti.uId = (UINT_PTR)pWnd->GetSafeHwnd(); // Handle of the tool
- SendMessage(TTM_ADDTOOL, 0, (LPARAM)&ti);
- }
Using CToolTipCtrlExt in Your Dialog
- Include Header:
- C++
- #include “ToolTipCtrlExt.h”
- Declare Member:
- C++
- CToolTipCtrlExt m_ctrl_tooltip_ext;
- OnInitDialog Setup:
- C++
- BOOL CMyDialog::OnInitDialog() {
- // … existing initialization …
- m_ctrl_tooltip_ext.Create(this); // ‘this’ refers to your dialog
- m_ctrl_tooltip_ext.Display_tooltip_text(“Saves the Data”, &m_ctrl_btn_save);
- // … add more tool-tips as needed …
- return TRUE; // …
- }
Let’s Test It! Run your project. Hover your mouse over the designated controls and see the tool-tips appear.
Customization Possibilities
Our CToolTipCtrlExt now encapsulates basic tool-tip setup. Think about enhancements:
- Dynamic Text: Change tool-tip text based on user actions.
- Styling: Experiment with colors, borders, and even hyperlinks inside the tool-tip.