Detecting column index of the item clicked

The HitTest() function provided by the CListCtrl class returns only the row index of the item that falls under the point being tested. The HitTest() also has the drawback that it fails if the point is not directly over the first column. To determine the row of the item, we use GetItemRect() to get the rectangular bounds of each visible row and use PtInRect() to determine if the point falls within this rectangle. Once we know the row, we use GetColumnWidth() to determine the bounding rect for each cell and then test the point against each of these bounding rectangles.
// HitTestEx	- Determine the row index and column index for a point
// Returns	- the row index or -1 if point is not over a row
// point	- point to be tested.
// col		- to hold the column index
int CMyListCtrl::HitTestEx(CPoint &point, int *col) const
{
	int colnum = 0;
	int row = HitTest( point, NULL );
	
	if( col ) *col = 0;

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

	// Get the top and bottom row visible
	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 ) )
				{
					if( col ) *col = colnum;
					return row;
				}
				rect.left += colwidth;
			}
		}
	}
	return -1;
}
 

Date Last Updated: April 3, 1999



Comments

  • GHD news De plus en plus de gens commencent à utiliser lisseur GHD en Norvège

    Posted by jdhgbi668 on 07/16/2013 10:39am

    Tige droite GHD veille à ce que le style ne reçoit pas trop chaud pour les cheveux Farget. C'est en fait assez simple: différents types de cheveux Trenger choses différentes températures pour y réagissent de style. La chaleur est plus facile Gjennom peu cheveux épais enn. Par conséquent, le Satin Hair 7 Colour tige droite un réglage de chaleur intuitive qui laisse deg avancer sinn calme température banquets précise le type de cheveux (peu, les cheveux épais normal). Et même si vous Bruker bouton d'alimentation une jolie G. uregjerlige tresses, alors vous ne serez pas utsette ditt de cheveux à des températures supérieures à 200 ° C. Obtenez d'excellents résultats de coiffage danger uten des températures Hoye et de nouvelles de la belle hårfargen votre long demandes. [url=http://ghdpascherferfr.blinkweb.com/]lisseur ghd pas cher[/url] GHD droit tige conteneur livfullheten et lambeaux de cheveux Farget. Près de la rivière pour s'assurer que la chaleur est répartie uniformément, ne devient jamais Hoy, reduserer La fargebevaringsteknologi unique avec IONTEC décoloration av Fargen en stylisme de 70% * et rend le Fargen obtient appareils de coiffage beaucoup plus glansfull.GHD ne fait pas ditt de cheveux terne et sec. Moi, sur IMot: ils empêchent fuktighetstap de style par y infliger ditt de cheveux satengioner unique! Ces ladde négatif ionène célébrations segment à la chevelure ladde positif ditt et reduserer sec, krusete cheveux et tiltrekker fuktighetspartikler de Lufta et leur envoyer votre le Trenger de cheveux le plus. [url=http://ghdpascherfer.tripod.com/]ghd lisseur pas cher[/url] Lisseur GHD est un outil de style professionnel avec revêtement avancé de perles en céramique pour une distribution uniforme de la chaleur et de douceur glissent à revêtement céramique normal. Il ne sera pas coincé dans les cheveux et le rendre brillant et droite à zéro tid.Høytpresterende redresseur avec cordon de revêtement en céramique et chauffage rapide à 10 sekunder.Den fonctionnalités réglage automatique de la tension pour le bon fonctionnement dans le monde, il s'éteint automatiquement après 60 minutes et il a un fil à charnière de 3 mètres. Une pochette de rangement résistant luxueux et chauffage inclus.

    Reply
  • Fantastisch werkt door monster beats

    Posted by mrswanzi on 06/06/2013 04:30am

    [url=http://koptelefoon-monsterbeats.webspawner.com/]beats by dre kopen[/url] Zoals bij de rest van de Beats-producten, zijn ook de urBeats verkrijgbaar in verschillende kleuren en voorzien van de nodige Beats-verwijzingen. In minder subtiele vorm is het Beats-logo aangebracht, waardoor de Beats-kenner al op afstand een set urBeats kan spotten! De urBeats zijn verkrijgbaar in een witte en zwarte uitvoering. Zo is er voor ieder wel wat wils! [url=http://koptelefoon-monsterbeats.tumblr.com/]beats by dre[/url] Beats by Dr Dre breidt gamma uit een draagbare muziekspeler, De voorbije zomer kenden de koptelefoons van Beats by Dr Dre een grote populariteitsgroei. De toestellen richtten zich vooral op actieve jongelui die op een stijlvolle manier hun muziek overal willen meenemen. Met de nieuwe Executive-koptelefoon denkt het merk nu ook aan de professionele zakenlui.Dit apparaat komt met een ingebouwde microfoon, waardoor je telefoongesprekken kan voeren zonder je hoofdtelefoon af te doen. De hoofdtelefoon heeft in vergelijking met zijn voorgangers een strak en volwassen design meegekregen en komt enkel in combinatie van grijs en zwart. [url=http://koptelefoon-monsterbeats.manifo.com/]Beats by dre Goedkope[/url] Voor diverse andere merken reden genoeg ook toenadering te zoeken bij een grote artiest. Mode zit van oudsher stevig verweven in de Amerikaanse hip hop en rap cultuur. De uitingen die artiesten dragen worden door (jonge) fans makkelijk geadopteerd. Dr. Dre geldt in deze cultuur nog altijd als een invloedrijk persoon. Door de samenwerking met de Amerikaanse rapper aan te gaan, legde Monster direct het fundament voor een succesvolle introductie van de Beats hoofdtelefoons. De aanwezigheid van Dr. Dre zorgde voor een fundamentele verandering in hoofdtelefoonland. Niet langer was het product een noodzaak, maar meer een accessoire. Beats by Dr. Dre Studio hoofdtelefoons: Kleurrijke kleur

    Reply
  • ghd glattejern populære familie, som skal produktet

    Posted by motherdhmm on 05/30/2013 11:58am

    [url=http://www.buy-beatsdrdre.com/category/2012-dr-dre-beats-outlet]dr dre beats[/url] Bliv en køber dille. På grund af dette, ofte forekommer falsk, så flere og flere mennesker køber ægte ghd glattejern. Vores butik, selv om salget af ghd håret sort. Men vi er regelmæssige ghd glattejern produkter. Fandt du ikke bringe alle former for falske brand skader. Vores produkt kort med det fysiske kort, er nøjagtig det samme. For at sikre sande og pålidelige produkter. Og vi sælger billige ghd glattejern, 7 * 24 online-funktioner, kan du købe på ethvert tidspunkt. Så længe du har valgt den ønskede type, udfylde personlige oplysninger, osv. relaterede emner, kan produktet blive leveret direkte til din ventende hænder. Venligst købe ghd glattejern produkter følelser før, se på vores privacy policy, Om os, transport, FAQ og mere relevante politikker, vil dette hjælpe dig til at købe vores produkter. Tak for dit samarbejde. [url=http://www.blog.cheapbeatsbydre.co.nz/monster-headphone]monster beats headphone[/url] . . Fart for at købe det. [url=http://www.buy-beatsdrdre.com/]beats by dre headphones[/url] Det har længe været bevist at ghd utvivlsomt er markedsledende med verdens bedste glattejern. Vi har hele sortimentet / udvalget af ghd glattejern til de bedste priser og her hos NiceHair.dk får du også leveret dit ghd glattejern direkte til døren helt og aldeles gratis.

    Reply
  • 1 specific double turn on adidas

    Posted by Updatatweda on 05/05/2013 11:55pm

    J [url=http://www.adidaskutuja.com/]アディダス[/url] cgRvf DmjUxl AzhHew AmwO [url=http://www.adidaskutuja.com/adidas-originals-c-4.html]adidas originals[/url] anDtvXfr JnpFzfMnyK [url=http://www.adidaskutuja.com/adidas-superstar-c-2.html]アディダス スタンスミス[/url] pg NpfMuv [url=http://www.adidaskutuja.com/jeremy-scott-c-5.html]アディダス 通販[/url]ZkgKtv TqjTiq

    Reply
  • Lightweight perceptive – Nike Let off TR Befit in jump 2013 3 series

    Posted by Tufffruntee on 04/24/2013 07:22pm

    Nike Free TR Suited 3 salient features is to purchase the brand-new design: Nike On the loose 5 soles improved bending Groove; new tractor pattern making training more focused when; lighter ballast, the permeability is stronger, and more trendy shoe designs not not exhort shoes [url=http://markwarren.org.uk/property-waet.cfm]air max 90 uk[/url] more serene wearing, barefoot training feel, but also more stylish appearance. Nike On the house TR Fitting 3 provides supreme lateral perseverance, you can have the legs in the lap boost during training. Strong vamp majuscule letters breathable mesh, lower soap up's consonant design can be [url=http://markwarren.org.uk/goodbuy.cfm]nike free[/url] seen through it. Lightweight, ragged, thin bubbles matter familiar at hand merest occasional seams, more amenable, advocate is stronger. Lack more mainstay, factor of a training vex, foam come in more parts of the shortage after flexibility, effervescence loose. Say stand-in tongue moisture wicking mock materials, flat on your feet, refrain from living feet dry and comfortable. Phylite [url=http://markwarren.org.uk/goodbuy.cfm]nike free run uk[/url] midsole offers lightweight surprise sustained, outstanding durability and stable outsole can do to greatly adjust the total avoirdupois of the shoe. Qianzhang pods on the outsole and heel-shaped Unripened rubber enhances the shoe multi-directional purchase on different surfaces.

    Reply
  • Interesting

    Posted by snareenactina on 01/03/2013 09:15am

    usyet A study by the Federal Reserve Bank of Chicago published recently found little evidence to support the argument of a skills shortage driving up unemployment. Sharonsj–your claim may be a more humanist, liberal point of view, but it is still an amusing conspiracy theory blaming Southern Republicans and big business for stealing from widows and orphans. Well, maybe you are half correct. If sj means Jesuit, I expected better. Secondly, that the regime’s officially published inflation rate of 6.2 percent is fabricated. The real inflation rate is 16 percent, according to Lang. fundable Budget's van hire service can accommodate all of your needs to a very high standard. Whatever your payload and dimension requirements, no job is too big or small for our fleet. You may be looking to move house, or perhaps relocate a whole office, but whatever you need van hire for, we have the right vehicle for you at unbeatable prices. We have a large fleet of small, medium and large vans, you will find the vehicle that's right for you. redso God does not care about the nation, he cares about each and every one of you. I pray for your soul. copygrant Combined empezar That trade continued with few interruptions until 1638, when it was prohibited on the ground that the ships were smuggling priests into Japan. sccp Sort: daytona A large share of the leading states’ institutions and residents have embraced the digital economy. Most of these states also have a solid innovation infrastructure that fosters and supports technological innovation, and many have a good quality of life coupled with high levels of domestic and foreign immigration of highly skilled knowledge workers. homicides Free subscriptions to our current and future global publications are available.

    Reply
  • Missing licencing information

    Posted by freds72 on 11/16/2010 11:48am

    Would it be possible to precise licencing terms for the related code source? Regards Frederic

    Reply
  • Misses the last row

    Posted by Mike Pliam on 04/28/2007 03:17am

    Has no one noticed that this technique misses the last visible row? How to fix that ?

    Reply
  • help me!

    Posted by Legacy on 08/05/2002 12:00am

    Originally posted by: hhh

    where can i get the point parameter piont in function HitTestEx(CPoint &point, int *col) const from?
    when the mouse point on the ListCtrl,how can i get the point? help me ?tanks a lot!

    Reply
  • Also can use SubItemHitTest

    Posted by Legacy on 05/31/2000 12:00am

    Originally posted by: wen111

    also can use SubItemHitTest of the CListCtrl for functions like "OnLButtonDown" which don't have a struct passed (see Matt Parker's post below). You can check the definition of
    
    LVHITTESTINFO struct in MSDN library.

    OnLButtonDown(UINT nFlags, CPoint point)
    {
    LVHITTESTINFO lvhti;
    lvhti.pt = point;
    GetListCtrl().SubItemHitTest(&lvhti);

    if(lvhti.flags & LVHT_ONITEM)
    {
    CString str;
    str.Format("iItem = %d, iSubItem = %d", lvhti.iItem, lvhti.iSubItem);
    AfxMessageBox(str);
    }
    }

    • Does not work

      Posted by SteveS on 08/20/2004 03:31pm

      This does not work for items in a listview unless the user happens to be over the first column of the list.

      Reply
    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: September 19, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT In response to the rising number of data breaches and the regulatory and legal impact that can occur as a result of these incidents, leading analysts at Forrester Research have developed five important design principles that will help security professionals reduce their attack surface and mitigate vulnerabilities. Check out this upcoming eSeminar and join Chris Sherman of Forrester Research to learn how to deal with the influx of new device …

  • A majority of organizations are operating under the assumption that their network has already been compromised, or will be, according to a survey conducted by the SANS Institute. With many high profile breaches in 2013 occurring on endpoints, interest in improving endpoint security is top-of-mind for many information security professionals. The full results of the inaugural SANS Endpoint Security Survey are summarized in this white paper to help information security professionals track trends in endpoint …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds