Tiptoe Through the ToolTips With Our All-Encompassing ToolTip Programmer's Guide
|I'll provide a comprehensive primer on adding tips to your application, from adding simple MFC-supplied ToolTips to writing custom TitleTips. Along the way, I'll even give you some pointers on adding ToolTips to your Web pages, including a simple ActiveX button control that has ToolTips.
|This article assumes you're familiar with Win32, MFC, and ActiveX controls.|
Code for this article: Tooltip.exe (215KB)
Roger Jack is an independent consultant specializing in OOD, Windows GUI, and OLE. He can be reached via email at firstname.lastname@example.org.|
ToolTips make using an application a lot easier. If you don't know what clicking on a toolbar button will do, just move your cursor over the toolbar button and wait for the ToolTip to appear. Although the status bar can provide more information than a ToolTip, your eyes do not have to travel to the bottom of the window to see a ToolTip.
Other types of tips have started to appear in other situations as well. There are TitleTips to extend the title of tree or listbox controls, DataTips to provide details about data in the window, and ToolTips for Web pages. In this article, I'll provide a comprehensive primer on adding tips to your application, from adding simple MFC-supplied ToolTips to writing custom TitleTips. Along the way, I'll even give you some pointers on adding ToolTips to your Web pages, including a simple ActiveX button control that has ToolTips. But before I begin discussing the specifics, let's briefly review MFC class support for ToolTips.
MFC Class Support for Tips
MFC has two classes that support ToolTips, CToolTipCtrl and CWnd. CToolTipCtrl encapsulates the functionality of the standard ToolTip control (found in the Common Controls DLL) and, therefore, can be used to create and manage a ToolTip control directly. In general, a single ToolTip can support multiple tools, which are just particular rectangles in a window and may or may not be child windows. It is also possible to have a single tool that fills the entire window. Information concerning a tool is sometimes passed through a TOOLINFO structure, which contains various fields: a handle to the window that contains the tool, an ID or window handle for the tool, a rectangle for the position of the tool, and information concerning the text for the tool. One of the most important methods is CToolTipCtrl::RelayEvent, which is used to relay mouse events to the ToolTip for processing. It makes sense to send mouse events to the ToolTip because it needs to determine when to display or hide a ToolTip. Unfortunately, CToolTipCtrl does not encapsulate all of the functionality of the standard ToolTip. For instance, CToolTipCtrl::SetDelayTime does not support all of the possible delay times. I sometimes had to use the raw Windows® messages and notifications because of the lack of total encapsulation. All ToolTip messages begin with the prefix "TTM_", and all ToolTip notifications begin with the prefix "TTN_". I will use this class extensively later, so I won't go into anymore detail here.
Microsoft recently enhanced the DLL that contains the ToolTips control (comctl32.dll) with Microsoft® Internet Explorer 4.0 (IE 4.0). The two-part MSJ article, "Previewing the Common Controls DLL for Microsoft Internet Explorer," (beginning in October, 1996) does an excellent job describing the new features. The new features include owner-draw, multiline, custom color ToolTips, and support for ToolTips that can track along with the mouse. There is a TTM_GETDELAYTIME message to get various delay times and a TTM_POP message to hide the ToolTip. Unfortunately, as I write this article, Microsoft has not yet added support for the new features in CToolTipCtrl. Therefore, I have to use CWnd::SendMessage to implement the functionality I'm showing you here. (The upcoming Visual Studio should have the long-awaited commctl.h file with the updated definitionsEd.)
The CWnd class provides basic support for adding ToolTips to a window. Figure 1 shows the CWnd member functions that provide ToolTip support. CWnd::EnableToolTips enables or disables ToolTips for a window and should be called before calling any of the other methods. Note, however, that there is a flaw in CWnd::EnableToolTips: when you call CWnd::EnableToolTips with FALSE, it eventually calls another method that sends a message to deactivate the ToolTip. When you call CWnd::EnableToolTips with TRUE, it never reactivates the ToolTip.
CWnd::OnToolHitTest is called by the framework and you can override it to hit-test the tool area. The first argument, point, is the location of the cursor in client coordinates. Use this to compare the cursor to the known positions of your tools (or buttons). The second parameter is the TOOLINFO structure I described previously. I'll show you how to override CWnd::OnToolHitTest later.
CWnd::FilterToolTipMessage is normally called for you by CWnd::PreTranslateMessage. You may call CWnd::FilterToolTipMessage directly (typically from your own PreTranslateMessage function) if CWnd::PreTranslateMessage is not being called for you, and I'll show you how later. CWnd::CancelToolTips hides a displayed ToolTip. The bKeys parameter is set to TRUE to hide the ToolTip when a key is pressed. It is important to understand that, even though CWnd::CancelToolTips is a static member function, it only affects ToolTips managed by CWnd. In other words, it has no affect on a CToolTipCtrl that you create in your own code.
Behind the scenes, CWnd implements its ToolTip functionality by creating a CToolTipCtrl and managing it for you. It stores a pointer to the ToolTip as an m_pToolTip member variable of a hidden AFX_THREAD_STATE structure. This structure is used by MFC to store thread-specific information. CWnd provides no documented support for accessing this ToolTip directly.
Adding Simple ToolTips with MFC
Microsoft has made it simple to add ToolTips to toolbar buttons. In fact, if you use AppWizard, it is virtually automatic. To add ToolTips, make certain that you check the "Docking toolbar" checkbox when you generate your application with AppWizard. This causes AppWizard to insert an m_wndToolBar into CMainFrame. m_wndToolBar is a CToolBar that gets initialized in CMainFrame::OnCreate. The CToolBar class has built-in support for ToolTips. AppWizard adds strings to the resource file that CToolBar uses as ToolTips for the standard toolbar buttons.
It is easy to modify the ToolTip strings after you have generated the application. Open the toolbar in the resource view. Double-click any toolbar button to display the Toolbar Button Properties dialog for that button, then edit the prompt line after the \n to change the ToolTip text. For example, in Figure 2, editing "Open" after the \n modifies the ToolTip text. The string before the \n is the text that appears in the status line when the ToolTip is displayed.
Figure 2 Toolbar properties
As I mentioned, the ToolTip text is stored in the string table. The string ID of the ToolTip text is equal to the ID of the ToolBar button. In Figure 2, the string ID would be ID_ FILE_OPEN. Microsoft's support for toolbar ToolTips is so easy to use that not much can go wrong. The only problem I have ever encountered has been the result of somebody accidentally overwriting the strings in the string table.
Adding ToolTips to Modal Dialog Boxes
You have probably seen dialogs that have ToolTips for each individual control. This is very useful if the purpose of the control is not immediately obvious. Knowledge Base article Q141758 ("How to Add Tooltips for Controls to an MFC Modal Dialog Box") describes how to implement ToolTips in MFC dialogs, so I will only briefly describe the steps here. For MFC version 4.0 or greater, you need to perform the following steps, assuming that the dialog box already exists in your application:
For versions of MFC earlier than 4.0, CDialog::PreTranslateMessage is not automatically called by CDialog::DoModal, so you have to do some additional work to relay mouse events to the ToolTip control. More specifically, you must override CWinApp::ProcessMessageFilter to relay events to the ToolTip. CWinApp::ProcessMessageFilter is called by the MFC framework's hook function to react to certain Windows messages. See the Knowledge Base article for more details, including specific coding examples.
- Add a CToolTipCtrl member variable to the protected or private section of your dialog class.
- Add a control member variable for each control that will have a tip. You can add the control member variables through the Member Variable tab of ClassWizard.
- Override CDialog::OnInitDialog and call CToolTipCtrl::Create. Then call CToolTipCtrl::AddTool for each control that has a ToolTip. Pass the address of the control member variable and the text of the ToolTip as parameters.
- Override CDialog::PreTranslateMessage and call CToolTipCtrl::RelayEvent for each message passed to CDialog::PreTranslateMessage. This insures that the ToolTip control gets all the necessary mouse messages.
Adding ToolTips to Your Web Page
Like applications, Web pages can benefit from ToolTips. There are two obvious ways to use ToolTips on Web pages: ToolTips for graphics and ToolTips for ActiveX controls. The sample control for this article is a button that I wrote to demonstrate how simple it is to add ToolTips to ActiveX controls. Figure 3 shows both the ActiveX control and a graphic image. The ActiveX control is the button with the smiley face. The graphic is the little bit of "art" just below the button.
Figure 3 Web page ToolTip
Adding a ToolTip to a graphic image is simple because this functionality is built into HTML (see Figure 4). The line
<img src="Image.gif" height=48 width=48 alt="Image ToolTip" >
provides the name and size of the image. The portion that says "Image ToolTip" is the actual ToolTip text that appears when you place the cursor over the image. It is also possible to add HotSpots to the image and create multiple ToolTips, but that is really beyond the scope of this article. I just want to give you a feel for how easy it is to add ToolTips via HTML.
The ActiveX control is a button with a ToolTip. Why would I bother making a button when I can add a three-dimensional image to the Web page that looks like a button anyway? Well, there are two reasons. First, a button is more realisticit moves in and out the way a real button should when the user clicks on it. Second, I wanted to show you how to add ToolTips to ActiveX controls, and a button is about the simplest control that I could use.
I used AppWizard to initially generate the control. I turned on the "Activate when visible" option and turned all other options off. For the "Which window class, if any, should this control subclass?" option, I selected BUTTON. There is a significant amount of boilerplate code generated by AppWizard that is superfluous to the main point of
this article. I will focus primarily on the code that I added, which is all contained in CWebButtonCtrl (see Figure 5 for a partial listing). Let's look at a couple of data members first. CWebButtonCtrl::m_bToolTipEnabled is TRUE if ToolTips are enabled. CWebButtonCtrl::m_strToolTipText contains the text for the ToolTip. I added both of these variables with ClassWizard and they represent OLE properties that are updated automatically by the MFC framework when the property is changed.
Moving on to the methods, CWebButtonCtrl::PreCreateWindow manipulates the CREATESTRUCT structure passed to it. Notice that I made the button owner-draw by applying the BS_OWNERDRAW style bit. I needed to make the button owner-draw so I could avoid drawing the focus rect when the button is active. Otherwise, the focus rect would always be visible. As a side effect, this also means that I have to override CWebButtonCtrl::OnOcmDrawItem to handle all drawing for the button. CWebButtonCtrl::OnCreate loads a bitmap for the button by calling BM_SETIMAGE. It also calls CWebButton::EnableToolTips to take advantage of the CWnd support for ToolTips.
The CWebButtonCtrl::OnMouseMove, CWebButtonCtrl::OnLButtonDown, and CWebButtonCtrl::OnLButtonUp methods all work similarly; they all call CWnd::RelayToolTipEvent. The CWebButtonCtrl::RelayToolTipEvent method makes a non-const copy of the passed message and calls CWnd::FilterToolTipMessage. I made a copy of the passed message because CWnd::FilterToolTipMessage requires a non-const pointer to the message. I could have cast the pointer to a non-const, but this is dangerous since CWnd::FilterToolTipMessage could then modify the message. Normally, CWnd calls CWnd::FilterToolTipMessage automatically in CWnd::PreTranslateMessage. However, in an ActiveX control the mouse messages never get to CWnd::PreTranslateMessage because it is only called as a result of keyboard input. CWnd::PreTranslateMessage is used primarily to handle keyboard accelerators. In a regular MFC application, CWnd::PreTranslateMessage is called as a result of CWinThread::PumpMessage.
CWebButtonCtrl::OnToolHitTest is called by CWnd::FilterToolTipMessage, and I overrode the default implementation to properly fill in the passed TOOLINFO structure. It only fills in TOOLINFO if ToolTips are enabled for the control. A ToolTip will only be displayed if TOOLINFO is filled in. The other tests for NULL and size are sanity checks. When it does fill in TOOLINFO, the function sets the rect member of TOOLINFO to the size of the client rect. In other words, this makes the entire button a single tool. It sets the lpszText member of TOOLINFO to the LPSTR_
CALLBACK. The ToolTip then sends the TTN_NEEDTEXT notification to get the text for the ToolTip. CWebButtonCtrl::OnToolNeedText handles the TTN_NEEDTEXT notification message from the ToolTip control by copying the string in m_strToolTipText into the szText data member of the passed TOOLTIPTEXT structure.
As you can see, the implementation of the ActiveX control relies on the CWnd support for ToolTips. Knowledge Base article Q141871 describes another method for adding ToolTips to ActiveX Controls: it shows how to create a CToolTipCtrl and call AddTool and UpdateTipText. A version of an ActiveX control using that technique is included with the downloadable source code (see page 5 for details). The amount of code required for both techniques is about the same in this example. Since I use the latter technique in the next tip, I want to expose you to CWnd support for ToolTips here.
I want you to be aware of the limitations of my implementation. First, there is a problem if you resize the control. The size of the tool does not get adjusted. This is not a real-world problem because you usually don't resize a button on a Web page after the Web page has been loaded. Second, a real-world ActiveX control would require code signing to create an authentication certificate. Otherwise, any user of the Web page will get a warning screen. This sample control is not signed. Third, the image is hardcoded into the button. A real-world ActiveX button should have the ability to load images dynamically.
I used the ActiveX Control Pad, which is available for free from Microsoft at http://msdn.microsoft.com/workshop/misc/cpad/default.asp, to add the control to my
Web page. Figure 4 shows
the HTML code that was inserted. As you can see,
the HTML includes values for OBJECT ID, WIDTH, HEIGHT, and CLASSID. There is also a list of parameters or properties for the control. The parameter name ToolTipText (with a value of "WebButton ToolTip Test") is the actual ToolTip text for the button. The line
is the beginning of a short VBScript routine that I wrote to respond to a button click. When you click the button, a "WebButton was clicked" message box appears.
DataTips are used to provide more detailed information about data that is displayed in a window. For instance, Microsoft uses DataTips in Visual C++® to make it easy to see variable contents. You just place your cursor on a variable when you are debugging and a tip pops up to display the contents of the variable. DataTips are useful in any situation in which more detail is available for an object in a window than can reasonably fit in the window.
Figure 6 DataTip sample
In this example, I use the new ToolTip features made available with the IE 4.0 Common Controls DLL to create DataTips that contain information about displayed circles (see Figure 6). I create circles of various sizes and colors in random locations in the window. When the cursor is over a circle, a multiline DataTip appears that shows the position, radius, and color of the circle. The color of the DataTip text is the same color as the circle. The multiline and text color features are only available with IE 4.0 installed.
I used AppWizard to generate a single document application with print preview turned off. I left all other settings set to their defaults. I created or modified three classes to implement the DataTip demo: CCircle, CDTDocument, and CDTView.
CCircle is a simple class that handles the drawing and hit-testing of a circle (see Figure 7 for the hit-testing code). CCircle::m_CenterPoint, CCircle::m_nRadius, and CCircle::m_Color hold the center, radius, and color of the circle, respectively. CCircle::Initialize takes a centerpoint, radius, and color as arguments and uses them to initialize the corresponding data members of a circle. I chose to have CCircle::Initialize initialize the data members rather than pass arguments in the constructor because it's easier to create an array of circles in CDTDocument. You'll see what I mean when I discuss CDTDocument below.
CCircle::Draw takes a pointer to a device context where the circle should paint itself. It calculates the bounding rectangle of the circle, creates an appropriately colored brush, and then uses CDC::Ellipse to draw the circle into the device context. CCircle::HitTest takes a point to be tested and uses the Pythagorean theorem (a2 + b2 = c2) to determine if the point is actually in the circle by checking if c2 is less than the circle's radius. I created an inline Square function to make the CCircle::HitTest code more readable. CCircle::GetColor, CCircle::GetCenter, and CCircle::GetRadius are inline methods that return the data members m_Color, m_CenterPoint, and m_nRadius, respectively. I made these member functions and the CCircle::Draw and CCircle::HitTest member functions const because they do not affect the internal state of the class. In other words, they maintain the constness of the class. This is good programming practice because it lets you use constant instantiations of CCircle.
CDTDemoDoc is derived from CDocument (which is included in the source code for this articlesee page 5 for details on downloading the source code). It holds an array of CCircles and provides CDTDemoDoc::GetCircleCount and CDTDemoDoc::GetCircle to access information concerning the array. CDTDemoDoc::GetCircleCount takes a zero-based index that represents an offset into the array. CDTDemoDoc::m_CircleArray holds the CCircles and has a size of CIRCLECOUNT. I could have made this array public, but I didn't do that for two reasons. First, it's easier for me to change the implementation if I hide it. I might, for instance, want to use the CArray template in the future to create a variable-sized array. Second, I want to return const references to users of CDTDemoDoc::GetCircle. This makes it impossible for the user of CDTDemoDoc to accidentally modify the circles in the array. CDTDemoDoc::CDTDemoDoc calls CCircle::Initialize for each circle in the array. CCircle::Initialize makes it easy to create a fixed-size array because I don't have to pass parameters to the constructor of CCircle. Otherwise, I would have had to create the array dynamically. I used the rand function to randomize the position of the circles. Notice that by seeding the srand function with the current time, there is a high probability that the position of each circle will be different each time that you run the application.
CDTDemoView is responsible for displaying the circles and managing the DataTip (see Figure 8). CDTDemoView::m_ ToolTip holds the ToolTip that is used as a DataTip. I wanted this example to show you how to use the CToolTipCtrl class directly rather than using the CWnd support for ToolTips. However, even if I wanted to use the CWnd support, I couldn't because I need direct access to the ToolTip so that I can send messages to it. CWnd does not provide any documented way to access the ToolTip that it creates, and I wouldn't want to rely on implementation details. CDTDemoView::m_pCircleHit is the current circle hit by the mouse. CDTDemoView::m_pCircleHit can be NULL if no circle is currently hit.
CDTDemoView::OnInitialUpdate creates the DataTip and prepares it for use. I call m_ToolTip.Create and pass TTS_ALWAYSTIP so that the DataTip displays whether the application is active or not. I then call m_ToolTip.AddTool and pass CDTDemoView as the window that contains the tool. Because CToolTipCtrl::AddTool has default parameters of LPSTR_TEXTCALLBACK and lpRectTool set to NULL and nIDTool set to zero, the entire window will be considered a tool and the TTN_NEEDTEXT notification message will be sent to CDTDemoView. This notification allows me to set the text of the DataTip as in CDTDemoView::OnToolTipNeedText.
I send several messages to the DataTip to prepare it for use. TTM_SETMAXTIPWIDTH is sent with a large value (SHRT_MAX) in lParam for the maximum tip width. This forces the ToolTip to respect newline characters in a string (a new feature with the IE 4.0 Common Controls DLL). Next, I send the TTM_SETDELAYTIME message three times. The first time wParam is set to TTDT_AUTOPOP, which represents the time before a ToolTip disappears. It is set to a large (SHRT_MAX) value in lParam. This, in effect, turns off autopop so I can control when the DataTip disappears. The second time wParam is set to TTDT_INITIAL, which is the delay time between when the cursor stops moving in a circle and the DataTip first appears. This is set to 200 milliseconds so it comes up quickly. And finally, TTDT_RESHOW sets the delay time before another ToolTip window is displayed when the cursor is moved from one circle to another. It is also set to 200 milliseconds. Why didn't I just use CToolTipCtrl::SetDelayTime to set the delay times? Unfortunately, CToolTipCtrl::SetDelayTime does not allow you to set any delay time except TTDT_AUTOMATIC.
CDTDemoView::OnDraw and CDTDemoView::HitTest are fairly straightforward. CDTDemoView::OnDraw iterates through the collection of circles. For each circle, it calls CCircle::Draw. CDTDemoView::HitTest checks to see if the passed point is over a circle. It does this by iterating over the array of circles and calling CCircle::HitTest. Notice that the hit-testing is done in reverse order. This is the opposite of CDTDemoView::OnDraw, which is necessary in order to deal with the z-order of the circles. For example, if circle B is drawn on top of circle A, then to hit-test properly you must check circle B first.
CDTDemoView::OnToolTipNeedText intercepts the TTN_NEEDTEXT notification message from m_ToolTip. Its main responsibility is to perform hit-testing and adjust the DataTip text. It first gets the current cursor position and converts the position to client coordinates. It does a sanity test to see if the mouse is in the client area of the view. If I don't do this, I could break regular toolbar ToolTips because the main frame needs to get TTN_NEEDTEXT notifications for toolbar processing. CDTDemoView::OnToolTipNeedText will automatically get all TTN_NEEDTEXT messages if the view is active. The bHandledNotify variable indicates whether the message should be passed up to the main frame. If the cursor is in the client area, I check to see if a circle has been hit and store the results of the test in the m_pCircleHit member variable. This variable is also used in CDTDemoView::OnMouseMove. If a circle has been hit, I create a multiline string with the center, radius, and color values of the circle. This string is copied into the szText member of the TOOLTIPTEXT structure that is passed. Finally, I set the color of the DataTip text by sending a TTM_SETTIPTEXTCOLOR message. The wParam is the new color for the text and it is set to the same color as the circle (another feature from the IE 4.0 Common Controls DLL). If the circle has not been hit, szText is set to an empty string.
CDTDemoView::PreTranslateMessage relays the mouse events of interest to the DataTip. It does this by calling CToolTipCtrl::RelayEvent.CDTDemoView::PreTranslateMessage is called for every message that is posted to this window. It is easier to call CToolTipCtrl::RelayEvent here because I don't have to override every mouse event to relay that mouse event to the DataTip. This is similar to the CWnd's ToolTip implementation.
CDTDemoView::OnMouseMove is used to hide and show the DataTip based on the hit-testing of the circle. It calls the HitTest member function to see if the cursor is over a circle. If the cursor is not over a circle or if it is over a different circle than last time CDTDemoView displayed a DataTip, then CDTDemoView::OnMouseMove hides the DataTip by calling m_ToolTip.Activate(FALSE). The FALSE indicates that the DataTip should be turned off and hidden. Next, if a circle has been hit, I immediately reactivate the DataTip by calling m_ToolTip.Activate(TRUE) and set CDTDemoView::m_pCircleHit to the new circle. So, when the circle has changed I deactivate the circle and then immediately reactivate it. I do this to force the DataTip to ask for new text through TTN_NEEDTEXT. This allows me to update the text with the new information for the circle. Incidentally, IE 4.0 is supposed to have a TTM_POP message that will hide the ToolTip, but this message was not available in the version of the commctrl.h file that I had.
Home Brew Tips: Adding TitleTips
TitleTips are tips that elongate a truncated item in a control so that you can see all of the item. For instance, Visual C++ 4.x has TitleTips in its Project Workspace. If a class name in the Project Workspace is too long to see all of it, a TitleTip appears that displays the full text. This makes it possible to use the Project Workspace without scrolling horizontally and without having to make it wider. I created a demo that makes TitleTips for a listbox. However, you could use similar techniques to add TitleTips to other types of controls as well. The code that I wrote can work with either regular (non-owner-draw) listboxes or owner-draw listboxes. I filled both listboxes with some of my favorite programming and software engineering books (see Figure 9).
Figure 9 TitleTip sample application
You might think that I could use the ToolTip's owner-draw feature (made available with the IE 4.0 Common Controls DLL) for implementing TitleTips. However, the width of the ToolTip window is calculated based on the text width of the displayed item. In other words, you do not have direct control over the width of the ToolTip control. This doesn't work well in an owner-draw listbox because you may want to display something other than text. Besides, I think it is important to know how to create a tip from scratch because there is always a chance that the standard tip won't provide some functionality that you require for your application. For instance, you might want to create an animated or speaking tip.
Figure 10 Class Diagram for TitleTip Demo
Figure 10 contains a Booch class diagram that shows the relationship between the classes relevant to this example. The CListBox class is a standard MFC class that encapsulates listbox functionality. The CTitleTipListBox class is derived from CListBox and is responsible for creating and managing the TitleTip for the listbox. CTitleTipListBox can be used directly if you are implementing a regular listbox. The CTitleTip class is derived from CWnd and represents the actual TitleTip. The CODListBox class is an owner-draw listbox that inherits from CTitleTipListBox. If you want to create an owner-draw listbox, you must derive it from CTitleTipListBox and override CTitleTipListBox::GetIdealItemRect. I'll discuss CTitleTipListBox::GetIdealItemRect in more detail later.|
The CTitleTip class is a window that represents the TitleTip (see Figure 11). CTitleTip::m_pszWndClass is a static data member used to hold the registered class name for the window. It is static because it only needs to be registered once for all instances of CTitleTip. CTitleTip::m_nItemIndex is the index of the listbox item that is currently displayed. This can be the constant CTitleTip::m_
nNoIndex if no item is displayed. CTitleTip::m_pListBox
is the parent of the TitleTip. The parent must be a listbox because I need to retrieve information from it to display
CTitleTip::CTitleTip registers a new window class by calling AfxRegisterWndClass and storing the class name in CTitleTip::m_pszWndClass. I call AfxRegisterWndClass so I can register a window class with the CS_SAVEBITS class style flag. The CS_SAVEBITS class style flag is an optimization that causes Windows to save the portion of any window obscured by the TitleTip as a bitmap. As a result, Windows does not need to send a WM_PAINT message to the window underneath the TitleTip when the TitleTip disappears. CTitleTip::Create creates the TitleTip as a popup window. It only adds a border to the TitleTip window if the listbox is a regular listbox because Windows automatically adds borders to owner-draw listboxes before it sends WM_DRAWITEM. Notice that CTitleTip::m_pszWndClass is passed as the window class name to CWnd::CreateEx. CTitleTip::IsListBoxOwnerDraw returns TRUE if the parent listbox is owner-draw. It figures this out by interrogating the style bits on the listbox.
CTitleTip::Show is responsible for showing the TitleTip. The DisplayRect parameter is the location and size of the TitleTip in parent client coordinates. The nItemIndex parameter is the listbox item index to be displayed. I optimized the routine so it only invalidates and adjusts the size and position of the TitleTip if it has changed. CWnd::SetWindowPos is called to adjust the TitleTip window. The first parameter is set to wndTopMost so that the TitleTip will always be on top of all other windows. The SWP_NOACTIVATE flag is passed so that the window does not get the focus. Since the TitleTip does not need any keyboard input, it never needs to get the focus. CTitleTip::Hide hides the TitleTip by calling CWnd::ShowWindow with SW_HIDE.
CTitleTip::OnPaint draws the TitleTip differently if the parent listbox is owner-draw versus regular. If the parent listbox is owner-draw, it creates and initializes a DrawItemStruct similar to how Windows initializes the DrawItemStruct when it is going to send WM_DRAWITEM. The one important difference is that, instead of initializing the hDC structure member to the device context of the listbox, it initializes the hDC to the device context of the TitleTip window. It then calls m_pListBox->DrawItem, passing the address of the DrawItemStruct. The net result is that the listbox actually draws the item into the TitleTip window. Pretty clever! This is the advantage of object-oriented programming and well-defined interfaces. The listbox doesn't know or care where it is actually drawing the itemit just knows how to draw it. CTitleTip does not know how to draw the owner-draw item, but it knows how to properly initialize DrawItemStruct and call CListBox::DrawItem. On the other hand, if the parent listbox is a regular listbox, the CTitleTip does all of the drawing itself. Fortunately, this is not too hard. It gets the appropriate text and font from the parent listbox, adjusts the device context, fills the background, and draws the text.
CTitleTipListBox is responsible for managing and displaying the TitleTip (see Figure 12). CTitleTipListBox::m_ LastMouseMovePoint is the last known position of mouse. CTitleTipListBox::m_bMouseCaptured indicates whether the CTitleTipListBox is currently capturing the mouse. CTitleTipListBox::m_TitleTip is an instance of CTitleTip that gets displayed. CTitleTipListBox::m_nNoIndex is a constant used to indicate that nothing is selected in the listbox.
CTitleTipListBox::GetIdealItemRect calculates the ideal item size and position. The nIndex parameter is the index of the item you want. The lpRect-passed parameter is used to return the ideal size and position in client coordinates. You must override this method if your listbox is an owner-draw listbox, and I'll show you how CODListBox overrides this method later. If you don't override this method and your listbox is owner-draw, then CTitleTipListBox::GetIdealItemRect emits a TRACE statement. However, if the listbox is a regular listbox, this method automatically calculates the ideal item size and position. It first calls CListBox::GetItemRect to calculate the height and width of the item. The width of the item returned by CListBox::GetItemRect is the width of the listbox, not the width of the text. To calculate the actual width of the text, I get the text and font for the item and then call CDC::GetTextExtent. Finally, I set lpRect to the maximum of the item width or the calculated text width (plus some space around the edges for aesthetic reasons).
CTitleTipListBox::AdjustTitleTip displays or hides the TitleTip as necessary. The nNewIndex parameter is the index of the listbox item to display. This can be the constant m_nNoIndex if no item is to be displayed. It creates a TitleTip if one has not already been created. If the new index is m_nNoIndex, then it hides the TitleTip. Otherwise, it gets the ideal item rect by calling CTitleTipListBox::GetIdealItemRect. If the ideal item rectangle is the same as the rectangle returned by CListBox::GetItemRect, there is no need for a TitleTip so it hides the TitleTip. Otherwise, it adjusts the ideal item rectangle so that it will fit within the screen and shows the TitleTip. If a TitleTip is visible, I capture the mouse so that I know when to hide the TitleTip. In other words, if the user moves the cursor so that it is not over any item, I need to hide the TitleTip; if the TitleTip is not visible, then I release the capture of the cursor. CTitleTipListBox::CaptureMouse captures the cursor. It stores the position of the cursor in client coordinates in CTitleTipListBox::m_LastMouseMovePoint. It also sets the m_bMouseCaptured flag to TRUE to indicate that the cursor is now captured.
CTitleTipListBox::IsAppActive returns TRUE if the application that contains the listbox is active. It determines this by getting the active window and testing to see if it is the same as, or a child of, the top-level parent of the application. This method is used in CTitleTipListBox::
OnMouseMove to make certain that the TitleTip is displayed only when the application is active.
CTitleTipListBox::OnContentChanged hides the TitleTip and is called when various events occur that could change the contents of the listbox. For instance, the LB_INSERTSTRING message, which inserts a string in a listbox, could make the displayed TitleTip invalid because the cursor would be over a different string after the insertion. The message map shows what particular events are handled through the use of the ON_MESSAGE macro. Wondering why I didn't use CWnd::PreTranslateMessage to intercept these messages? Well, I tried, but CWnd::PreTranslateMessage only intercepts messages from the message queue. These intercepted messages appear to be the result of Windows calling SendMessage, which bypasses the message queue.
CTitleTipListBox::OnMouseMove does hit-testing to see if a TitleTip needs to be displayed. It only does hit-testing if the application that contains the listbox is active and the cursor has actually moved from its last position. I found that Windows sometimes sends multiple WM_MOUSEMOVE messages for the same cursor position, so I use the m_LastMouseMovePosition data member to filter out these unnecessary messages. CTitleTipListBox::OnMouseMove then does a check to make certain that the cursor is in the client area of listbox. The cursor could be outside the client area because I'm capturing the mouse. An amusing side-effect of not doing this test is that the TitleTip would sometimes appear for items that aren't currently visible in the listbox. Anyway, if the mouse is in the client area of the listbox, CTitleTipListBox::OnMouseMove iterates over all the items and tests to see if the cursor is over an item. If so, it uses that item as the new index to pass to CTitleTipListBox::AdjustTitleTip.
CTitleTipListBox::OnSelchange handles the LBN_
SELCHANGE notification message from windows. If the selection has changed, then it may need to adjust the TitleTip to reflect the changed selection state. For example, if the new selection is the same as the item that is being displayed by the TitleTip, then the TitleTip needs to be updated to reflect a selected item. Notice that CTitleTipListBox::OnSelchange respects whether the listbox is multiple or single selection. In the case of multiple selection, it calls CListBox::GetCaretIndex. In the case of single selection, it calls CListBox::GetCurSel. Handling the LBN_
SELCHANGE notification message also makes it possible for TitleTips to be displayed properly when the user selects items with the keyboard instead of the mouse.
CTitleTipListBox::OnKillFocus and CTitleTipListBox::OnDestroy are relatively simple. CTitleTipListBox::
OnKillFocus hides the TitleTip unless the new focus window is the TitleTip window. This is necessary so that the TitleTip is automatically hidden when the user tabs away from the listbox. CTitleTipListBox::OnDestroy hides and destroys the TitleTip.
CTitleTipListBox::OnLButtonDown invalidates the TitleTip so it can be redrawn in case the selection state has changed. I temporarily turn off capturing before calling the base class because I found that I broke selection tracking if I didn't. Selection tracking occurs when you drag the selection rectangle from listbox item to listbox item. Since I'm not privy to the listbox internals, I can only speculate as to the cause of the problem. Maybe the listbox control needs to capture the mouse itself in order to support selection changes on left mouse-button down.
CTitleTipListBox::OnLButtonUp captures the mouse if the TitleTip window is visible and CTitleTipListBox is not already capturing the mouse. CTitleTipListBox::PreTranslateMessage watches for other types of mouse button messages and makes the view active if the listbox is in a view. I did this to mimic the default behavior of an MFC view when it gets a WM_MOUSEACTIVATE message. Otherwise, it could miss a mouse activate message when the user clicks on the TitleTip window.
CODListBox is an example of an owner-draw listbox with TitleTips (see Figure 13). CODListBox::m_nEdgeSpace is a constant used to add extra space around text. CODListBox::m_nFontHeight is a constant that represents the desired height of the font used for displaying items. CODListBox::m_Font is the font used for displaying an item. CODListBox::CODListBox creates the font (m_Font) for drawing in a listbox.
CODListBox::GetIdealItemRect overrides the CTitleTipListBox method of the same name. As you can see, the implementation is similar to the base class's implementation, except that it is using m_Font for the font. I actually could have made this work without overriding the base class if I had called CWnd::SetFont to set the font for the listbox. However, I wanted to show you how to override the method for other cases. For instance, if you want to display graphic images in the listbox, you would have to override CTitleTipListBox::GetIdealItemRect.
CODListBox::DrawItem draws the item based on the DrawItemStruct. This code is similar to the code found in CTitleTip::OnPaint, except that the colors are red and white instead of the default colors. Remember that CTitleTip may actually be calling this method to draw into its window.
CODListBox::MeasureItem calculates the height of an item based on font and desired edge space. This is only called once by Windows because the listbox style is LBS_OWNERDRAWFIXED. It may be called for each item in the listbox if the style is LBS_OWNERDRAWVARIABLE.
CTTDemoDlg holds the two listboxes, and most of the code was generated by AppWizard (see Figure 14). I added the m_RegListBox and m_ODListBox data members for the regular and owner-draw listboxes, respectively. The only other code that I added is in CTTDemoDlg::OnInitDialog, where I subclassed both listboxes by calling CWnd::SubclassWindow. I also loaded both listboxes from a static array, pszItemArray.
Well there you have itfive tips on using tips. I hope this will inspire you to add more ToolTips, TitleTips, and DataTips to your applications and Web pages. Better yet, maybe you'll invent a new type of tip that all of us can use in our applications. If you do, make sure you pass it along to the rest of us!
Special thanks to Bill Kinsley and others at AM Communications, Inc.
See the sidebar: Adding Delays to TitleTips
© 1997 Microsoft Corporation. All rights reserved. Legal Notices.