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

IT Offers

Comments

  • 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
  • If I don't use mouse

    Posted by Legacy on 08/03/1999 12:00am

    Originally posted by: Wen

    If I use tab key and space bar to push the column
    how can I detect the item number

    • how about selecting using ARROW KEYS?

      Posted by Maverick5877 on 07/13/2005 05:53am

      Maybe you have an idea about getting the selected column index using arrow keys... 
      i have problems on many ListCtrl events.. i.e.
      
         void ...OnLvnItemchangedListService(NMHDR *pNMHDR, LRESULT *pResult)
      {
      	
          LPNMLISTVIEW pNMLV = reinterpret_cast(pNMHDR);
         //   pNMLV->subitem is always zero even if I have selected on    
         //columns other than the first one..
      }
      
      with   OnNMClick().. subitem just works fine but 
      with all other event messages specially with the LVN_????() messages, 
      the subitem  value of pNMHDR is not properly updated..

      Reply
    • And if there is no click?

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

      What if you're just hovering over the control and you don't click?

      Reply
    Reply
  • Fix so that hit test works with reordered columns

    Posted by Legacy on 07/05/1999 12:00am

    Originally posted by: Andrew Skowronski

    The latests version of the List Control allows user
    
    to reorder columns with drag and drop when
    the LVS_EX_HEADERDRAGDROP flag is set.

    This HitTestEx function doesn't work properly for
    such a reordered list control. Forunately the
    fix pretty straightforward.

    I've renamed the colnum variable to colpos to try
    and be a little more clear.
    I've changed the "for" loop to look at the columns
    in the order they are currently sorted, not in
    the order of their index.

    Note:
    I happen to know the maximum number of columns.
    To be more general you could allocated an
    array of size nColumnCount.

    Here is the change to function:

    HitTestEx(CPoint &point, int *col) const

    ....

    // Now find the column

    ASSERT( nColumnCount <= MAX_NUM_COLUMNS );
    int aColumnOrder[ MAX_NUM_COLUMNS ];

    VERIFY( ListView_GetColumnOrderArray(GetSafeHwnd(),
    nColumnCount,
    aColumnOrder) );

    for( colpos = 0; colpos < nColumnCount; colpos++ )
    {
    int colwidth = GetColumnWidth(aColumnOrder[ colpos ]);
    if( point.x >= rect.left
    && point.x <= (rect.left + colwidth ) )
    {
    if( col ) *col = aColumnOrder[ colpos ];
    return row;
    }
    rect.left += colwidth;
    }

    Reply
  • Stack & Heap Based Singleton

    Posted by Legacy on 05/17/1999 12:00am

    Originally posted by: Thierry Bensoussan

    The problem about Stack & Heap based singleton is discussed
    in Pattern Hatching.

    Although the use of a static member seems to be cleaner,
    this solution is not usable in a multi-threaded environnement
    where several threads can call the Instance() method
    concurently.

    In this context, the only right solution seems to be the one
    using a static pointer to the Singleton with a "Destroyer"
    inner class for memory management as described in
    "Pattern Hatching".

    However if you're not in a multi-threaded environnement, the
    static instance solution seems right.

    Reply
  • Loading, Please Wait ...

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

Go Deeper

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds