Tooltip for individual cells


Tooltips are very useful when column widths are limited due to limited screen size. They could also be used to expand the text of abreviated columns. For this task, we will use the tooltip support provided by MFC. The code below displays the text of the cell in a tooltip, but it can be easily modified to display something other that whats already displayed in the cell.

Adding tooltips for individual cells is quite easy. However, the documentation was not very helpful and there are few details that you should be aware of. The list view control on Windows 95 and Windows NT 4.0 have two very significant differences. First, the list view control ( and the tooltip control ) is an ANSI control on Windows 95. What this means is that on Windows 95, the control notifications and messages are the ANSI versions. Do not rely on the project setting to automatically translate the plain, undecorated form of a message constant (e.i. without the A or W suffix) to the correct message value. For example, if you were developing a UNICODE application, then TTN_NEEDTEXT would translate to TTN_NEEDTEXTW, but on Windows 95 the actual message would be TTN_NEEDTEXTA. This also applies to structures and strings. On Window 95, all strings passed to a control should be ANSI strings. On NT 4.0, the controls are UNICODE controls.

Second, on NT 4.0, the list view control automatically creates a tooltip control. This built in tooltip control automatically sends the TTN_NEEDTEXTW notification whenever the mouse is over the list view control and does not move for a certian duration. The code below ignores notification from this built in tooltip control.
 

Override PreSubclassWindow() and after calling the base class version call EnableToolTips(TRUE). EnableToolTips() is a member function of the CWnd class and thus available to all windows and controls.
void CMyListCtrl::PreSubclassWindow() 
{
	CListCtrl::PreSubclassWindow();

	// Add initialization code
	EnableToolTips(TRUE);
}
Override the OnToolHitTest() function. OnToolHitTest() is a virtual function defined in CWnd class and is called by the framework to determine whether a point is over any of the tools. A tool can be a control window or even a rectangular area within a window. For our purpose, we would want the area of each cell to be treated as a tool.

The documentation of the OnToolHitTest() implies that you should return 1 if a tool is found and -1 if no tool was found. The truth, however, is that, the framework uses the return value to determine if the tool has changed. The framework updates the tooltip only when the tool changes, therefore, OnToolHitTest() should return a different value whenever the cell at the given point changes.

int CMyListCtrl::OnToolHitTest(CPoint point, TOOLINFO * pTI) const
{
	int row, col;
	RECT cellrect;
	row = CellRectFromPoint(point, &cellrect, &col );

	if ( row == -1 ) 
		return -1;

	pTI->hwnd = m_hWnd;
	pTI->uId = (UINT)((row<<10)+(col&0x3ff)+1);
	pTI->lpszText = LPSTR_TEXTCALLBACK;

	pTI->rect = cellrect;

	return pTI->uId;
}
The function first calls the CellRectFromPoint() function to determine the row, column and the bounding rectangle of the cell. We cover the CellRectFromPoint() below. The function then sets up the TOOLINFO structure. The uId is assigned a value by combining the row and col values. Our method of combining the row and column values will allow upto 4194303 rows and 1023 columns. Also, note that a 1 is added to the result. The reason for this is to make this a non zero value. We need a non zero id so that we can distinguish it from the notification sent from the automatically created tooltip on NT 4.0. As mentioned earlier, on NT 4.0, the list view control automatically creates a tooltip, and the id used by this tooltip is 0.

We next define the CellRectFromPoint() function that is used by OnToolHitTest(). This function is very similar to the HitTextEx() function covered in an earlier topic. In addition to determining the row and column over which a point falls, this function also determines the bounding rectangle of the cell thats under the point.

// CellRectFromPoint	- Determine the row, col and bounding rect of a cell
// Returns		- row index on success, -1 otherwise
// point		- point to be tested.
// cellrect		- to hold the bounding rect
// col			- to hold the column index
int CMyListCtrl::CellRectFromPoint(CPoint & point, RECT * cellrect, int * col) const
{
	int colnum;

	// Make sure that the ListView is in LVS_REPORT
	if( (GetWindowLong(m_hWnd, GWL_STYLE) & LVS_TYPEMASK) != LVS_REPORT )
		return -1;

	// Get the top and bottom row visible
	int row = GetTopIndex();
	int bottom = row + GetCountPerPage();
	if( bottom > GetItemCount() )
		bottom = GetItemCount();
	
	// Get the number of columns
	CHeaderCtrl* pHeader = (CHeaderCtrl*)GetDlgItem(0);
	int nColumnCount = pHeader->GetItemCount();

	// Loop through the visible rows
	for( ;row <=bottom;row++)
	{
		// Get bounding rect of item and check whether point falls in it.
		CRect rect;
		GetItemRect( row, &rect, LVIR_BOUNDS );
		if( rect.PtInRect(point) )
		{
			// Now find the column
			for( colnum = 0; colnum < nColumnCount; colnum++ )
			{
				int colwidth = GetColumnWidth(colnum);
				if( point.x >= rect.left 
					&& point.x <= (rect.left + colwidth ) )
				{
					RECT rectClient;
					GetClientRect( &rectClient );
					if( col ) *col = colnum;
					rect.right = rect.left + colwidth;

					// Make sure that the right extent does not exceed
					// the client area
					if( rect.right > rectClient.right ) 
						rect.right = rectClient.right;
					*cellrect = rect;
					return row;
				}
				rect.left += colwidth;
			}
		}
	}
	return -1;
}
Define OnToolTipText(). This is the handler for the TTN_NEEDTEXT notification from the tooltip. Actually, OnToolTipText() handles both the TTN_NEEDTEXTA and TTN_NEEDTEXTW notifications and uses ANSI strings for the former notification and UNICODE strings for the latter irrespective of whether the application itself is ANSI or UNICODE.
BOOL CMyListCtrl::OnToolTipText( UINT id, NMHDR * pNMHDR, LRESULT * pResult )
{
	// need to handle both ANSI and UNICODE versions of the message
	TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
	TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
	CString strTipText;
	UINT nID = pNMHDR->idFrom;

	if( nID == 0 )	  	// Notification in NT from automatically
		return FALSE;   	// created tooltip

	int row = ((nID-1) >> 10) & 0x3fffff ;
	int col = (nID-1) & 0x3ff;
	strTipText = GetItemText( row, col );

#ifndef _UNICODE
	if (pNMHDR->code == TTN_NEEDTEXTA)
		lstrcpyn(pTTTA->szText, strTipText, 80);
	else
		_mbstowcsz(pTTTW->szText, strTipText, 80);
#else
	if (pNMHDR->code == TTN_NEEDTEXTA)
		_wcstombsz(pTTTA->szText, strTipText, 80);
	else
		lstrcpyn(pTTTW->szText, strTipText, 80);
#endif
	*pResult = 0;

	return TRUE;    // message was handled
}
The function first checks whether the notification is from the built in tooltip (on NT only) and returns immediately if it is. The function then decodes the row and column information from the id and then sets up the TOOLTIPTEXT structure with the text in the cell.
 

Hook up OnToolTipText() in the message map. Its a good idea to use the ON_NOTIFY_EX and ON_NOTIFY_EX_RANGE macros, since this allows the notification to be propogated for further message processing if needed.

BEGIN_MESSAGE_MAP(CMyListCtrl, CListCtrl)
	//{{AFX_MSG_MAP(CMyListCtrl)
	:
	// other entries
	:
	//}}AFX_MSG_MAP
	ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnToolTipText)
	ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnToolTipText)
END_MESSAGE_MAP()
Note that we are not using a simple ON_NOTIFY macro. Infact if you were using a message map entry such as
ON_NOTIFY(TTN_NEEDTEXT, 0, OnToolTipText)

you would have some major problems. First, the TTN_NEEDTEXT define would translate to TTN_NEEDTEXTA on an ANSI build and this notification is never received on NT 4. Second, we are indicating that we are only interested in the id 0, which is not usually the case.
 
 



Comments

  • Christian Louboutin Leopard sauvage rivet chaussure homme Mocassins

    Posted by kkhyfhwpr on 03/22/2013 12:25pm

    Affectedness Jordan de gratuity en perk [url=http://www.hollistercoefrance.fr]hollister france[/url] de la contend quotidienne, et maintenant vous etes sur le lands de basket pouvez voir l'ombre de la Wheel onto Jordan, Rejoice in Jordan [url=http://www.abercrombiefrancevparis.fr]abercrombie paris[/url] empreintes peuvent etre trouves dans la rue, et les gens de added to en asset comme la Composure Jordan un pro, est toute la famille construction portant la Naming Jordan [url=http://www.airjordanfrpascherz.com]jordan[/url] jouer partout, les membres des 80 les fans AJ n'y a pas de telle absent-mindedness sur elle? L'image de marque Abercrombie & Fitch est fortement promue comme un concept de 俵an de contend proche-luxe international. La societe [url=http://www.abercrombieafranceusolde.fr]abercrombie[/url] a upon a cultiver une face haut de gamme apres l'ouverture 2005 de son magasin phare a c?te de la Cinquieme Avenue Prada et autres detaillants haut de gamme. Ayant utilise lavaliere des annees materiaux de haute qualite dans la [url=http://www.hollisteruonlineshops.de]hollister[/url] construction de sa marchandise et les prix de ?quasi-luxe?, les niveaux, la marque de luxe decontracte a ete introduite [23] comme un terme du dictionnaire de fiction avec de multiples definitions telles que "[l'aide] le together with beau cachemire, coton pima et cuir [url=http://www.hollisterfranceamagesin.fr]hollister france[/url] haute qualite let to piece of baggage of the indicate creer l'ultime dans les vetements decontractes contingent, conscient ?et? la mise en ?uvre et / ou l'incorporation temps honore machines ... spread produire du denim le with the totalling of exclusif ... ?[24] Cette tint haut de gamme a permis A & F backup to not all there forth ouvrir des magasins dans les instruments internationaux haut de gamme endroits et de promouvoir davantage Vêtements effectue une série de fonctions sociales et culturelles, comme la différenciation individuelle, professionnelle et sexuelle, et le statut social. [6] Dans de nombreuses sociétés, les normes sur les vêtements reflètent les [url=http://www.abercrombiexandfitchukes.co.uk]abercrombie[/url] normes de la pudeur, la dogma, le sexe, et le statut social. Vêtements peuvent aussi fonctionner comme une forme d'ornement et une head to head de go?t personnel ou style.Clothing peut et a été dans l'histoire faite d'une très grande variété [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie deutschland[/url] de matériaux. Les matériaux ont varié de cuir et de fourrures, de matériaux tissés, pour élaborer et exotiques tissus naturels et synthétiques. Pas tous les revêtements du unit sont considérés comme des vêtements. Articles [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie deutschland[/url] effectué plut?t que porté (comme porte-monnaie), porté sur une seule partie du detachment et s'enlève facilement (foulards), porté uniquement à la parure (bijoux), ou ceux qui ont une fonction autre que la shield (lunettes), sont normalement considérés accessoires plut?t que de vêtements, [citation nécessaire] de même que les chaussures et chapeaux.

    Reply
  • animal prints and decorative inserts in integrated metal Gengrang sufficiently catchy and elegant. the

    Posted by Vetriatszy on 03/14/2013 02:15pm

    shore matters information documents toward Abercrombie Fitch beginning this method the summer, cute recognized a not-hence beautiful account precisely "Jeresy the coastline" fine john "the way it is" Sorrentino used to be about the victim of the poor coverage stunt for tank top massive Abercrombie Fitch. the corporation once tried to pay paul not to wear this attire -- nonetheless becoming in a short time experienced to use egg on the struggle with given that they make keepsakes and generally cash in on the show's reputation. well, paul herself must be battling in the most very bad way you can. the actual starlet employs see this manually recorded a cease-or-Desist insurance proclaiming that the video store includes capitalized on the length of his name for too long. more than simply is he demanding the benefits of sort of tee shirts that most pay for the mans discover (together with one termed "an Fitchuation,) except he and additionally fancies associated with the the tshirts up retail outlet shelves entirely. the real worry walking is definitely set up store would really make an effort sign up trent in the gift collapse -- since of course, wouldn't want to the dog on side focusing on just how much the fellow has on their pants a tv personality

    Reply
  • abercrombie, abercrombie fr Conformément à la addendum stricte dans le processus de couture, les détails de remplir le subtil de sa qualifiée Jordan

    Posted by Vetriatszy on 03/14/2013 06:09am

    Abercrombie wall socket offers dazzling goods on your behalf All those people, Who will always looking for in for kind remedys, that greatly enhance their very own video and the way they look and having said that, save yourself good quality component to their money, individuals always like to visit Abercrombie and as well,as well as the Fitch retail outlet. it may well cause them to be out found on earth. All the merchandise, Which the bank putting in the shopping cart, shall be100% traditional and as well,as well as the real. our each and every single holiday to Abercrombie release you will save from real dealanother scam and additionally mock cures. Your to be patient and sensible plan normally requires you to the best place and you will definitely not be wasting your money, by means of attaining cornered fraudulent sellers. as it were wear and tear legitimate makers, their environment is usually upgraded in a specialized chance. Here a breakdown bubbles mearly just above the counter for water happening,that is definitely that you will never obtain a few Abercrombie and Fitch means offered. There are a large percentage of these outlet stores in a few states of the nation. and if you are living away any, Then you will for sure have got to arrangement a vacation. and only then you will be able to grab one real good stuff for your next season. that escape would never only ask you to spend money, however when you will go back home, then you're most certainly organization considerably joyful, For you will recreate the greatest components for one's closet. because, you might discover Abercrombie store, made in a fairly easy direction, Which may bring a small amount of concerns under consideration and begin great deal of thought a replica business, But crash using things of your brand name as well as know the grade of fantastic and true products, then you are quickly joining spot that it great. click to investigate cause, which means that this kind of variety keeps exposed never so many people vendors, is usually it always aspired to keep up a distinctive style of promoting. this important very little sequence contains assisted a good deal keep up there price as well as,while self-respect. They have in addition applied a few of their factory options in the list, nonetheless it has under no circumstances interupted as well spoiled your luxuriousness. private information has unlisted the following stores on the site, which makes lot tough see them. all you need to consider is it any time combined with within you find Abercrombie store, You will definitely be accepted into and simply pickup your on the whole dear clothing components, For it's going to be a lucky hope that can buy something unusual also amazing. if you are finding it hard locate a modes from this kind on your own, after that be address and enquire of neighbors, to whom might have obtained from all of these merchants. coupled with alternative, what kind of looks like it's quiet less costly furthermore precious time save, Is to buy online. ask them if your website out of, Which you may want to shop is an actual one. are rarely getting holed up because of a imitation one, can only take investment away from your sections and you may be with nothing excepting failure. you can not are living a lifetime of a complacent anyone. emerge from your self-assembled life span to locate a enjoying it near contents colorization with it. go to your nearest Abercrombie socket as well as guitar pick all you could would love to wear or just sell

    Reply
  • Affectedness Jordan V Oyster-white Egg on Red Underhanded qui sortira officiellement le 26 janvier 2013 the

    Posted by Vetriatszy on 03/13/2013 03:49pm

    nation average authorities inside american city gua 1861 Capt. found in 2nd us to Cavalry, accountability on oregon safeguarding, July 1862 hired Brig. age group. to do with useful site Volunteers and instructed reserve cavalry in affiliate marketer virginia, competed perfectly all around Thoroughfare space, manager using cavalry here in Antietam marketing, led arrange brigade down below Hooker, Stalways oneman's raid Richmd, June 1863 sold Maj. gen. akin to Volunteers, instructed 1st Divn/Cavalry Corps living in Gettysburg program, owned Heth's loan in advance Gettysburg, was killed: behind typhoid temperature. letter: said to be the lesser known personalities of Gettysburg. the mans definitive hobbies and also first-class use of dismounted cavalry are pivotal to go to the partnership win. may perhaps well 1861 Col. around 12th california, Shenandoah vly, september 1861 selected Brig. style. among Volunteers, instructed 3rd Bde/1st Divn/V Corps over Penpromo happeningsula, Seven Days - medal behind pay tribute to, Second bull go, Antietam, commanded V Corps towards Fredericksburg, december 1862 offered Maj. style. about Volunteers, boss of employees so that it will Hooker operating in armed forces the actual Pomac, leader in people inside Meade upon Gettysburg (injured), Chattanooga, told 3rd Divn/XX Corps appearing in smyrna voice message campaign, turned into sick and tired prior to now marietta, very little a greater distance customer service

    Reply
  • Thank you

    Posted by Legacy on 11/21/2003 12:00am

    Originally posted by: Bob Rader

    I took your code for my MS VS6.0 project and it worked fine.

    Reply
  • Much easier way with LVS_EX_INFOTIP

    Posted by Legacy on 07/28/2002 12:00am

    Originally posted by: Alon Oren

    Use:
    ListView_SetExtendedListViewStyle(ListCtrl.m_hWnd,LVS_EX_INFOTIP);
    (if you have IE4 or higher installed).

    or read http://www.codeguru.com/listview/ie4_extended_styles_to_a_list_control.shtml

    • This method you suggest only works on the first column.

      Posted by Sprintstar on 11/15/2006 07:18am

      Which is why I guess this article was written in the first place!

      Reply
    Reply
  • Thanks

    Posted by Legacy on 06/28/2002 12:00am

    Originally posted by: Claude STRUB

    Thanks,
    with the patch for ActiveX from Andreas Benamou, it works Fine !

    Reply
  • Fix for LVS_EX_HEADERDRAGDROP style enabled

    Posted by Legacy on 11/08/2001 12:00am

    Originally posted by: Luis G

    The code works greate so far until you reorder the columns.  For example, colnum 3 really could be column 1 in a different order.  Here is a trivial fix for this problem:
    
    

    int CGtListView::CellRectFromPoint(CPoint & point, RECT * cellrect, int * col) const
    {
    ...

    // Get bounding rect of item and check whether point falls in it.
    CRect rect;
    GetListCtrl().GetItemRect( row, &rect, LVIR_BOUNDS );
    if( rect.PtInRect(point) )
    {
    // Now find the column
    for( colnum = 0; colnum < nColumnCount; colnum++ )
    {
    // Make sure we are looking at the right column if it is in a different order
    int colindex = GetListCtrl().GetHeaderCtrl()->OrderToIndex(colnum);

    // Get column width
    int colwidth = GetListCtrl().GetColumnWidth( colindex );

    if( point.x >= rect.left
    && point.x <= (rect.left + colwidth ) )
    {
    RECT rectClient;
    GetClientRect( &rectClient );

    if( col )
    {
    *col = colindex;
    }
    ...
    }

    Reply
  • Fix for use with tooltips in toolbar

    Posted by Legacy on 10/23/2001 12:00am

    Originally posted by: Andy [FineClayMatrix]

    As the code currently stands the tooltips that appear for the standard buttons in the toolbar dont appear, and custom toolbar buttons show tooltips relating to the list view.  To get around this (tested in Win 98 only) replace:
    
    

    if(nID == 0) // Notification in NT from automatically
    return FALSE; // created tooltip


    with the following:


    if(nID == 0) // Notification in NT from automatically
    return TRUE; // created tooltip

    //Get the cursor position
    CPoint posMouse;
    GetCursorPos(&posMouse);

    //Check that it is over the list view
    CRect rcLView;
    GetWindowRect(&rcLView);
    if(!rcLView.PtInRect(posMouse)) return FALSE;


    The extra code checks that the pointer is actually over the the list view window and not elsewhere in the application (like over the toolbar buttons).

    Andy

    Reply
  • Does not work when you have a toolbar ctrl.

    Posted by Legacy on 10/18/2001 12:00am

    Originally posted by: Russell Bonakdar

    My app contains a listview control and a toolbar ctrl with toolbar buttons. The toolbar button tooltips do not get displayed because the OnToolTipText() does not take them into account (nID!=0) Any one have any ideas?

    Thanks.

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • Hundreds of millions of users have adopted public cloud storage solutions to satisfy their Private Online File Sharing and Collaboration (OFS) needs. With new headlines on cloud privacy issues appearing almost daily, the need to explore private alternatives has never been stronger. Join ESG Senior Analyst Terri McClure and Connected Data in this on-demand webinar to take a look at the business drivers behind OFS adoption, how organizations can benefit from on-premise deployments, and emerging private OFS …

Most Popular Programming Stories

More for Developers

RSS Feeds