Mega Code Archive

 
Categories / Delphi / VCL
 

ListView column index from cursor position (i.e. Right Click etc...)

Title: ListView column index from cursor position (i.e. Right Click etc...) Question: when trying to implement code in the ColumnRightClick event of a TListView all is fine and Column.Index is accurate as long as there is no Horizontal scroll-bar in the TListView, once a Scroll-Bar is in use the Column.Index is NOT the index of the actual column under your mouse cursor, using the code I've attached can guarntee accurate results. Answer: {=== Get the Column index of the ListView Column under the cursor ===} Function GetColumnAtCursor(Const iLvwHwnd:Integer): Integer; // Using: Windows; Var i,j,m,scrolPos:Integer; pt : TPoint; rct : TRect; Const LVM_GETCOLUMNWIDTH = 4125;//-- Instead of searching these constants, I've posted them here --\\ HDM_GETITEMCOUNT = 4608; LVM_GETCOLUMNORDERARRAY = 4155; //-- Get the ListView's horizontal scroll-bar position --\\ Function GetLvwHzScrolPos(Const lvwHwnd:Integer): Integer; Var si:TScrollInfo; begin si.cbSize := SizeOf(si); si.fMask := SIF_ALL; if IsWindow(lvwHwnd) And GetScrollInfo(lvwHwnd, SB_HORZ, si) then Result := si.nPos else Result := 0; end; begin Result := -1; scrolPos := GetLvwHzScrolPos(iLvwHwnd); //-- Get the ListView horizonatl Scroll-Bar position --\\ GetCursorPos(pt); //-- Get current cursor position --\\ GetWindowRect(iLvwHwnd, rct); //-- Get the ListView position on the screen --\\ i := WindowFromPoint(pt); //-- Get the cloumn header --\\ m := SendMessage(i, HDM_GETITEMCOUNT, 0, 0);//-- Get the columns count --\\ pt.X := Pt.X-rct.Left;//-- Adjust the cursor position to be relative to the control (as opposed to relative to screen) --\\ pt.Y := Pt.Y-rct.Top; j := scrolPos*-1; //-- Start adding the width of each column from the scrolled position --\\ For i:=0 To m-1 do begin //-- Get and add the acutal width of each ListView column --\\ j := j+ Integer(SendMessage(iLvwHwnd, LVM_GETCOLUMNWIDTH, i, 0)); //-- Once the width equals to the cursor position the column header is found --\\ if j=(pt.X) then begin Result := i; Break; end; end; end; //---------------------------------------------------------------------\\