List Box Hit Testing
I'm trying to determine which list box item the cursor is over when my parent window receives a WM_CONTEXTMENU message (the right mouse button was clicked). Unfortunately, the list box is owner-drawn with variable heights for each item, so it's not as simple as getting the index of the top visible item and doing some division, the actual visible area needs to be determined.
Does anyone know how this could be done?
You could try LB_ITEMFROMPOINT or LBItemFromPt.
List box hit testing doesn't work properly in Windows XP.
This is from code I found either at codeguru or codeproject. This is MFC, but you should be able to convert to Win32 quite easily.
UINT CAddSeqDlg::ItemFromPointNT(CPoint pt, BOOL& bOutside) const
// CListBox::ItemFromPoint does not work on NT.
if (m_lstFrames.GetCount()==0) return -1;
int nFirstIndex, nLastIndex;
nFirstIndex = m_lstFrames.GetTopIndex();
nLastIndex = nFirstIndex + m_lstFrames.GetCount();
bOutside = TRUE;
int nResult = -1;
for (int i = nFirstIndex;nResult==-1 && i<=nLastIndex;i++)
nResult = i;
bOutside = FALSE;
Really? I implemented the LB_ITEMFROMPOINT message in my program (running on XP) and it works fine. Gets me the item under the cursor or nothing. :confused:
Perhaps MSDN meant that the MFC encapsulation of that does not work.
Actually... this snippet could be quite useful indeed.
The problem with LB_ITEMFROMPOINT is that it always returns the list item nearest the cursor. If I want to be explicit and only get what's immediately underneath the cursor then your code modified slightly would give the correct result.
Cheers Bubba. ;)
Then modfiy away and hope it works for ya's. I needed this for a right click on a list box as well and the code works quite well.