Page 1 of 1

Listview Column Issues

PostPosted: Fri Apr 12, 2019 6:53 pm
by HsiaLin
I have an app that has 2 large ListView controls side by side. I need to be able to click on an
item and know which column was clicked so i can use the value from the clicked column.
I am attaching a tiny source to show what my issue is. I can get the column clicked as long as
the scrollbar has not been moved. This is limiting my ability to click on the last column and
get a proper result. For some reason once the scrollbar is moved, it ruins the column width
math and i have no idea why. Has anyone ever had this issue? If so what is the remedy.

Re: Listview Column Issues

PostPosted: Sat Apr 13, 2019 9:43 am
by HsiaLin
Finally figured it out by adding the scroll position to X.

This will fix it:
Code: Select all
//---------------------------------------------------------------------------

void __fastcall TForm1::ListView1MouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift, int X, int Y)
{
    TListItem *Item;
    int Wid;
    int Col;


    int hScroll = GetScrollPos(ListView1->Handle, SBS_HORZ);
    Item = ListView1->GetItemAt(0, Y);
    if((Item != NULL))
    {
       Wid =  0;
       Col = -1;
       do
       {
          Col++;
          if(Col == ListView1->Columns->Count - 1)
            break;
          Wid += ListView1->Column[Col]->Width;
       }
       while(!(X + hScroll < Wid));
       columnum = Col;
    }
    else
    {
       columnum = -1;
    }

    ShowMessage(L"You clicked column number " + IntToStr(columnum));

}

Re: Listview Column Issues

PostPosted: Wed Apr 17, 2019 1:45 pm
by rlebeau
HsiaLin wrote:Finally figured it out by adding the scroll position to X.


There is a much easier way - simply send the ListView's HWND a LVM_HITTEST message with wParam=-1. The return value will be the index of the item, and the output LVHITTESTINFO will contain the column index.

Re: Listview Column Issues

PostPosted: Wed Apr 17, 2019 9:21 pm
by HsiaLin
Ahh thanks for the info, had to use ListView_SubItemHitTest.
Seems there's always a better way.

Code: Select all
    LVHITTESTINFO htinfo = {0};
    htinfo.pt = Point(X, Y);
    ListView_SubItemHitTest(ListView1->Handle, &htinfo);
    ShowMessage(L"You clicked column number " + IntToStr(htinfo.iSubItem));

Re: Listview Column Issues

PostPosted: Wed Apr 17, 2019 10:39 pm
by rlebeau
HsiaLin wrote:had to use ListView_SubItemHitTest.


Yes, that is the one I was originally thinking of (the LVM_SUBITEMHITTEST message), I just couldn't remember the name of it (it has been a long time since I last needed to use it).